Error handling guide Go Fiber Chinese document 2.x

🐛 error handling

Fiber supports centralized error handling and allows you to record errors to external services or send custom HTTP responses to clients by returning errors to the handler.

Capture error

It must be ensured that Fiber can catch all errors when running the routing handler and middleware. You must return them to the handler function, where Fiber will capture and process them.

app.Get("/", func(c *fiber.Ctx) error {
    // Pass error to Fiber
    return c.SendFile("file-does-not-exist")
})

Fiber does not process by default panics . To Recover from the panic thrown by any handler in the stack, you need to include the following Recover middleware.

Example:

package main

import (
    "github.com/gofiber/fiber/v2"
    "github.com/gofiber/fiber/v2/middleware/recover"
)

func main() {
    app := fiber.New()

    app.Use(recover.New())

    app.Get("/", func(c *fiber.Ctx) error {
        panic("This panic is caught by fiber")
    })

    log.Fatal(app.Listen(":3000"))
}

You can use Fiber's custom error structure and use Fiber Newerror() passes an additional status code. Passing a message is optional; If left blank, it defaults to a status code message (404 equals ` not found ').

Example:

app.Get("/", func(c *fiber.Ctx) error {
    // 503 Service Unavailable
    return fiber.ErrServiceUnavailable

    // 503 is on vacation!
    return fiber.NewError(fiber.StatusServiceUnavailable, "On vacation!")
})

Default error handler

Fiber provides an error handler by default. For a standard error, the response is sent as 500 internal server errors. If the error is fiber.Error Type, the response is sent with the provided status code and message.

Example:

// Default error handler
var DefaultErrorHandler = func(c *fiber.Ctx, err error) error {
    // Default 500 status code
    code := fiber.StatusInternalServerError

    if e, ok := err.(*fiber.Error); ok {
        // Overwrite the status code if fiber Error type
        code = e.Code
    }
    // Set content type: text / plain; charset=utf-8
    c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)

    // Returns a status code with an error message
    return c.Status(code).SendString(err.Error())
}

Custom error handler

In initialization Fiber instance You can use Config Set up a custom error handler.

In most cases, the default error handler should be sufficient. However, custom error handlers come in handy if you want to catch different types of errors and take appropriate actions, such as sending notification emails or recording errors to the central system. You can also send a custom response to the client, such as an error page or just a JSON response.

The following example shows how to display error pages for different types of errors.

Example:

// Create a new fiber instance with a custom configuration
app := fiber.New(fiber.Config{
    // Override default error handler
    ErrorHandler: func(ctx *fiber.Ctx, err error) error {
        // The default status code is 500
        code := fiber.StatusInternalServerError

        // If it's fiber* Error, retrieve the custom status code.
        if e, ok := err.(*fiber.Error); ok {
            code = e.Code
        }

        // Send custom error page
        err = ctx.Status(code).SendFile(fmt.Sprintf("./%d.html", code))
        if err != nil {
            // In case SendFile fails
           return ctx.Status(fiber.StatusInternalServerError).SendString("Internal Server Error")
        }

        // Return from handler
         return nil
    },
})

// ...

Special thanks Echo and Express Framework in error handling.

This article was first published in LearnKu.com On the website.

Added by robogenus on Fri, 21 Jan 2022 09:16:19 +0200