错误处理

未匹配的标注

错误处理

当程序产生了一个特定的 http 错误的时候,你可以定义你自己的错误处理代码。

错误代码是大于或者等于 400 的 http 状态码,像 404 not found 或者 500 服务器内部错误。

代码例子:

package main

import "github.com/kataras/iris"

func main(){
    app := iris.New()
    app.OnErrorCode(iris.StatusNotFound, notFound)
    app.OnErrorCode(iris.StatusInternalServerError, internalServerError)
    // 为所有的大于等于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")
}

func internalServerError(ctx iris.Context) {
    ctx.WriteString("Oups something went wrong, try again")
}

func index(ctx context.Context) {
    ctx.View("index.html")
}

本文章首发在 LearnKu.com 网站上。

本译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

原文地址:https://learnku.com/docs/iris-go/10/erro...

译文地址:https://learnku.com/docs/iris-go/10/erro...

上一篇 下一篇
讨论数量: 0
发起讨论 只看当前版本


暂无话题~