Golang - Iris Web Framework #9: Xử lý lỗi HTTP

17 tháng 02, 2020 - 2161 lượt xem

Bạn có thể xác định trình xử lý của riêng mình khi xảy ra mã lỗi http cụ thể.

Mã lỗi là mã trạng thái http lớn hơn hoặc bằng 400, như 404 not found và 500 internal server.

Ví dụ:

package main

import "github.com/kataras/iris/v12"

func main(){
    app := iris.New()
    app.OnErrorCode(iris.StatusNotFound, notFound)
    app.OnErrorCode(iris.StatusInternalServerError, internalServerError)
    // to register a handler for all "error"
    // status codes(kataras/iris/context.StatusCodeNotSuccessful)
    // defaults to < 200 || >= 400:
    // app.OnAnyErrorCode(handler)
    app.Get("/", index)
    app.Run(iris.Addr(":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")
}

 Tìm hiểu thêm về View.

 


The Problem type

Iris đã tích hợp hỗ trợ cho Chi tiết sự cố cho HTTP API.

Context.Problem viết một phản hồi vấn đề JSON hoặc XML. Hành vi chính xác như Context.JSON nhưng với mặc định ProblemOptions.JSON thụt lề của " " và một loại nội dung phản hồi của "application/problem+json" thay thế.

Sử dụng các trường options.RenderXML and XML để thay đổi hành vi này và gửi phản hồi của loại nội dung "application/problem+json" thay thế.

func newProductProblem(productName, detail string) iris.Problem {
    return iris.NewProblem().
        // The type URI, if relative it automatically convert to absolute.
        Type("/product-error"). 
        // The title, if empty then it gets it from the status code.
        Title("Product validation problem").
        // Any optional details.
        Detail(detail).
        // The status error code, required.
        Status(iris.StatusBadRequest).
        // Any custom key-value pair.
        Key("productName", productName)
        // Optional cause of the problem, chain of Problems.
        // .Cause(other iris.Problem)
}

func fireProblem(ctx iris.Context) {
    // Response like JSON but with indent of "  " and
    // content type of "application/problem+json"
    ctx.Problem(newProductProblem("product name", "problem details"),
        iris.ProblemOptions{
            // Optional JSON renderer settings.
            JSON: iris.JSON{
                Indent: "  ",
            },
            // OR
            // Render as XML:
            // RenderXML: true,
            // XML:       iris.XML{Indent: "  "},
            // Sets the "Retry-After" response header.
            //
            // Can accept:
            // time.Time for HTTP-Date,
            // time.Duration, int64, float64, int for seconds
            // or string for date or duration.
            // Examples:
            // time.Now().Add(5 * time.Minute),
            // 300 * time.Second,
            // "5m",
            //
            RetryAfter: 300,
            // A function that, if specified, can dynamically set
            // retry-after based on the request.
            // Useful for ProblemOptions reusability.
            // Overrides the RetryAfter field.
            //
            // RetryAfterFunc: func(iris.Context) interface{} { [...] }
    })
}

Đầu ra "application/problem+json"

{
  "type": "https://host.domain/product-error",
  "status": 400,
  "title": "Product validation problem",
  "detail": "problem error details",
  "productName": "product name"
}

Khi RenderXML được đặt thành true thì thay vào đó phản hồi sẽ được hiển thị dưới dạng XML.

Đầu ra "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>

Xem ví dụ đầy đủ tại _examples/routing/http-errors.

Phần tiếp theo chúng ta sẽ tìm hiểu về Subdomains (Tên miền phụ).

Bình luận

avatar
Nguyễn Hàn Duy 2020-02-17 10:10:56.404435 +0000 UTC
Cảm ơn tác giả
Avatar
* Vui lòng trước khi bình luận.
Ảnh đại diện
  0 Thích
0