github.com/gofiber/fiber/v2@v2.47.0/docs/guide/error-handling.md (about)

     1  ---
     2  id: error-handling
     3  title: 🐛 Error Handling
     4  description: >-
     5    Fiber supports centralized error handling by returning an error to the handler
     6    which allows you to log errors to external services or send a customized HTTP
     7    response to the client.
     8  sidebar_position: 4
     9  ---
    10  
    11  import Tabs from '@theme/Tabs';
    12  import TabItem from '@theme/TabItem';
    13  
    14  ## Catching Errors
    15  
    16  It’s essential to ensure that Fiber catches all errors that occur while running route handlers and middleware. You must return them to the handler function, where Fiber will catch and process them.
    17  
    18  <Tabs>
    19  <TabItem value="example" label="Example">
    20  
    21  ```go
    22  app.Get("/", func(c *fiber.Ctx) error {
    23      // Pass error to Fiber
    24      return c.SendFile("file-does-not-exist")
    25  })
    26  ```
    27  </TabItem>
    28  </Tabs>
    29  
    30  Fiber does not handle [panics](https://go.dev/blog/defer-panic-and-recover) by default. To recover from a panic thrown by any handler in the stack, you need to include the `Recover` middleware below:
    31  
    32  ```go title="Example"
    33  package main
    34  
    35  import (
    36      "log"
    37  
    38      "github.com/gofiber/fiber/v2"
    39      "github.com/gofiber/fiber/v2/middleware/recover"
    40  )
    41  
    42  func main() {
    43      app := fiber.New()
    44  
    45      app.Use(recover.New())
    46  
    47      app.Get("/", func(c *fiber.Ctx) error {
    48          panic("This panic is caught by fiber")
    49      })
    50  
    51      log.Fatal(app.Listen(":3000"))
    52  }
    53  ```
    54  
    55  You could use Fiber's custom error struct to pass an additional `status code` using `fiber.NewError()`. It's optional to pass a message; if this is left empty, it will default to the status code message \(`404` equals `Not Found`\).
    56  
    57  ```go title="Example"
    58  app.Get("/", func(c *fiber.Ctx) error {
    59      // 503 Service Unavailable
    60      return fiber.ErrServiceUnavailable
    61  
    62      // 503 On vacation!
    63      return fiber.NewError(fiber.StatusServiceUnavailable, "On vacation!")
    64  })
    65  ```
    66  
    67  ## Default Error Handler
    68  
    69  Fiber provides an error handler by default. For a standard error, the response is sent as **500 Internal Server Error**. If the error is of type [fiber.Error](https://godoc.org/github.com/gofiber/fiber#Error), the response is sent with the provided status code and message.
    70  
    71  ```go title="Example"
    72  // Default error handler
    73  var DefaultErrorHandler = func(c *fiber.Ctx, err error) error {
    74      // Status code defaults to 500
    75      code := fiber.StatusInternalServerError
    76  
    77      // Retrieve the custom status code if it's a *fiber.Error
    78      var e *fiber.Error
    79      if errors.As(err, &e) {
    80          code = e.Code
    81      }
    82  
    83      // Set Content-Type: text/plain; charset=utf-8
    84      c.Set(fiber.HeaderContentType, fiber.MIMETextPlainCharsetUTF8)
    85  
    86      // Return status code with error message
    87      return c.Status(code).SendString(err.Error())
    88  }
    89  ```
    90  
    91  ## Custom Error Handler
    92  
    93  A custom error handler can be set using a [Config ](../api/fiber.md#config)when initializing a [Fiber instance](../api/fiber.md#new).
    94  
    95  In most cases, the default error handler should be sufficient. However, a custom error handler can come in handy if you want to capture different types of errors and take action accordingly e.g., send a notification email or log an error to the centralized system. You can also send customized responses to the client e.g., error page or just a JSON response.
    96  
    97  The following example shows how to display error pages for different types of errors.
    98  
    99  ```go title="Example"
   100  // Create a new fiber instance with custom config
   101  app := fiber.New(fiber.Config{
   102      // Override default error handler
   103      ErrorHandler: func(ctx *fiber.Ctx, err error) error {
   104          // Status code defaults to 500
   105          code := fiber.StatusInternalServerError
   106  
   107          // Retrieve the custom status code if it's a *fiber.Error
   108          var e *fiber.Error
   109          if errors.As(err, &e) {
   110              code = e.Code
   111          }
   112  
   113          // Send custom error page
   114          err = ctx.Status(code).SendFile(fmt.Sprintf("./%d.html", code))
   115          if err != nil {
   116              // In case the SendFile fails
   117              return ctx.Status(fiber.StatusInternalServerError).SendString("Internal Server Error")
   118          }
   119  
   120          // Return from handler
   121          return nil
   122      },
   123  })
   124  
   125  // ...
   126  ```
   127  
   128  > Special thanks to the [Echo](https://echo.labstack.com/) & [Express](https://expressjs.com/) framework for inspiration regarding error handling.