1
0
mirror of https://github.com/kataras/iris.git synced 2025-12-18 10:27:06 +00:00

add some MVC error handle examples

This commit is contained in:
Gerasimos (Makis) Maropoulos
2020-08-18 23:14:11 +03:00
parent 35ab1de212
commit 4228dd8ea4
14 changed files with 324 additions and 3 deletions

View File

@@ -0,0 +1,60 @@
package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/mvc"
)
func main() {
app := iris.New()
app.RegisterView(iris.HTML("./views", ".html"))
// Hijack each output value of a method (can be used per-party too).
app.ConfigureContainer().
UseResultHandler(func(next iris.ResultHandler) iris.ResultHandler {
return func(ctx iris.Context, v interface{}) error {
switch val := v.(type) {
case errorResponse:
return next(ctx, errorView(val))
default:
return next(ctx, v)
}
}
})
m := mvc.New(app)
m.Handle(new(controller))
app.Listen(":8080")
}
func errorView(e errorResponse) mvc.Result {
switch e.Code {
case iris.StatusNotFound:
return mvc.View{Code: e.Code, Name: "404.html", Data: e}
default:
return mvc.View{Code: e.Code, Name: "500.html", Data: e}
}
}
type errorResponse struct {
Code int
Message string
}
type controller struct{}
type user struct {
ID uint64 `json:"id"`
}
func (c *controller) GetBy(userid uint64) interface{} {
if userid != 1 {
return errorResponse{
Code: iris.StatusNotFound,
Message: "User Not Found",
}
}
return user{ID: userid}
}

View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Client Error Page</title>
</head>
<body>
<h2>{{.Code}}</h2>
<h3>{{.Message}}</h3>
</body>
</html>

View File

@@ -0,0 +1,12 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Server Error Page</title>
</head>
<body>
<h2>{{.Code}}</h2>
<h3>{{.Message}}</h3>
</body>
</html>