Skip to content

Latest commit

 

History

History
43 lines (30 loc) · 1001 Bytes

custom-http-errors.md

File metadata and controls

43 lines (30 loc) · 1001 Bytes

自定义HTTP错误 / Custom HTTP Errors

You can define your own handlers when http error occurs.

当发生 HTTP 错误时,你可以定义自己的处理器。

package main

import (
	"github.com/kataras/iris"
)

func main() {

	iris.OnError(iris.StatusInternalServerError, func(ctx *iris.Context) {
        ctx.Write("CUSTOM 500 INTERNAL SERVER ERROR PAGE")
		// or ctx.Render, ctx.HTML any render method you want
		// 或者 ctx.Render、 ctx.HTML 任意你想要使用的渲染器方法
		ctx.Log("http status: 500 happened!")
	})

	iris.OnError(iris.StatusNotFound, func(ctx *iris.Context) {
		ctx.Write("CUSTOM 404 NOT FOUND ERROR PAGE")
		ctx.Log("http status: 404 happened!")
	})

	// emit the errors to test them
	// 发出错误测试
	iris.Get("/500", func(ctx *iris.Context) {
		ctx.EmitError(iris.StatusInternalServerError) // ctx.Panic()
	})

	iris.Get("/404", func(ctx *iris.Context) {
		ctx.EmitError(iris.StatusNotFound) // ctx.NotFound()
	})

	iris.Listen(":80")

}