Handle HTTP errors
You can define your own handlers when a specific http error code occurs. Error handlers can be registered per Party.
Error codes are the http status codes that are bigger than or equal to 400, like 404 not found and 500 internal server error.
Example code:
package main
import "github.com/kataras/iris/v12"
func main(){
app := iris.New()
app.RegisterView(iris.HTML("./views", ".html"))
app.OnErrorCode(iris.StatusNotFound, notFound)
app.OnErrorCode(iris.StatusInternalServerError, internalServerError)
// to register a handler for all error codes:
// app.OnAnyErrorCode(handler)
app.Get("/", index)
app.Listen(":8080")
}
func notFound(ctx iris.Context) {
// when 404 then render the template
// $views_dir/errors/404.html
ctx.View("errors/404.html")
// OR, if you had more paths and you want
// to suggest relative paths to the user:
// 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")
}Iris has the EnablePathIntelligence option which can be passed to app.Run/Listen method to auto-redirect a not found path to its closest match one, e.g "http://localhost:8080/contac" to "http://localhost:8080/contact". Enable it:
You can also force all paths to be lowercased by setting the ForceLowercaseRouting option:
The Problem type
Iris has builtin support for the Problem Details for HTTP APIs.
The Context.Problem writes a JSON or XML problem response. Behaves exactly like Context.JSON but with default ProblemOptions.JSON indent of " " and a response content type of "application/problem+json" instead.
Use the options.RenderXML and XML fields to change this behavior and send a response of content type "application/problem+xml" instead.
Outputs "application/problem+json"
When RenderXML is set to true then the response will look be rendered as XML instead.
Outputs "application/problem+xml"
Full example can be found at _examples/routing/http-errors.
Last updated
Was this helpful?