# 错误处理程序
当出现特定的http错误代码时,你可以定义自己的处理程序。
错误代码是大于或等于400的http状态代码,例如 404 not found a和500内部服务器错误。
示例代码:
```
package main
import "github.com/kataras/iris/v12"
func main(){
app := iris.New()
app.OnErrorCode(iris.StatusNotFound, notFound)
app.OnErrorCode(iris.StatusInternalServerError, internalServerError)
//为所有“错误”注册一个处理程序
// 状态代码(kataras/iris/context.StatusCodeNotSuccessful)
// 默认为 < 200 || >= 400:
// app.OnAnyErrorCode(handler)
app.Get("/", index)
app.Run(iris.Addr(":8080"))
}
func notFound(ctx iris.Context) {
// 当出现 404 时, 渲染模版
// $views_dir/errors/404.html
ctx.View("errors/404.html")
// 或者, 如果你有更多路径并且想要
// 向用户建议相对路径:
// suggestPaths := ctx.FindClosest(3)
// if len(suggestPaths) == 0 {
// ctx.WriteString("404 not found")
// return
// }
// ctx.HTML("Did you mean?<ul>")
// for _, s := range suggestPaths {
// ctx.HTML(`<li><a href="%s">%s</a></li>`, s, s)
// }
// ctx.HTML("</ul>")
}
func internalServerError(ctx iris.Context) {
ctx.WriteString("Oups something went wrong, try again")
}
func index(ctx iris.Context) {
ctx.View("index.html")
}
```
>了解有关 [视图](https://github.com/kataras/iris/wiki/View/) 的更多信息。
# 问题类型
Iris 内置了对 [HTTP API问题详细信息](https://tools.ietf.org/html/rfc7807)的支持。
`Context.Problem` 编写 JSON 或 XML 问题响应。行为与` Context.JSON` 完全一样, 但是默认的 `ProblemOptions.JSON` 缩进为 " ",响应内容类型为 "application/problem+json" 。
使用 `options.RenderXML `和 `XML` 字段来更改此行为, 并发送内容类型为 "application/problem+xml" 的响应。
```
func newProductProblem(productName, detail string) iris.Problem {
return iris.NewProblem().
// URI类型,如果是相对类型,它将自动转换为绝对类型。
Type("/product-error").
//标题,如果为空,则从状态代码获取。
Title("Product validation problem").
// 任何可选的详细信息。
Detail(detail).
//状态错误代码,必填。
Status(iris.StatusBadRequest).
// 任何自定义键值对。
Key("productName", productName)
// 问题的可选原因,问题链。
// .Cause(other iris.Problem)
}
func fireProblem(ctx iris.Context) {
// 响应类似 JSON,但缩进为 " " ,并且
// 内容类型为 "application/problem+json"
ctx.Problem(newProductProblem("product name", "problem details"), iris.ProblemOptions{
// 可选的 JSON 渲染器设置。
JSON: iris.JSON{
Indent: " ",
},
// 要么
// 呈现为 XML:
// RenderXML: true,
// XML: iris.XML{Indent: " "},
// 设置 "Retry-After" 响应头。
//
//可以接受:
// time.Time HTTP-Date,
// time.Duration, int64, float64, int 秒钟
// 或日期或持续时间的字符串。
// 例子:
// time.Now().Add(5 * time.Minute),
// 300 * time.Second,
// "5m",
//
RetryAfter: 300,
// 可以根据请求动态设置重试的函数(如果指定)。
// 对于ProblemOptions可重用性很有用。
// 覆盖RetryAfter字段。
//
// RetryAfterFunc: func(iris.Context) interface{} { [...] }
})
}
```
**输出 "application/problem+json"**
```
{
"type": "https://host.domain/product-error",
"status": 400,
"title": "Product validation problem",
"detail": "problem error details",
"productName": "product name"
}
```
当 `RenderXML` 设置为 `true` 的时候,,响应将呈现为 XML 格式。
**输出 "application/problem+xml"**
```
<Problem>
<Type>https://host.domain/product-error</Type>
<Status>400</Status>
<Title>Product validation problem</Title>
<Detail>problem error details</Detail>
<ProductName>product name</ProductName>
</Problem>
```
完整示例可以在 [_examples/routing/http-errors](https://github.com/kataras/iris/blob/master/_examples/routing/http-errors/main.go) 中找到。
