Skip to main content

Error Handling

We advocate centralized error handling by returning errors from middleware functions and handler functions. Then use a unified error handler function to log errors to external services and send custom HTTP responses to the client.

We can return a standard error instance or a *slim.HTTPError object.

For example, when the basic authentication middleware detects invalid credentials, it returns 401 (Unauthorized error) to abort the current HTTP request:

Authentication
e.Use(func(c slim.Context, next slim.HandlerFunc) error {
// Extract the credentials from HTTP request header and perform a security
// check

// For invalid credentials
return slim.NewHTTPError(http.StatusUnauthorized, "Please provide valid credentials")

// For valid credentials call next
// return next(c)
})

You can also return a slim.HTTPError instance with an error message slim.NewHTTPError(http.StatusUnauthorized). In this case, Slim will use the status text "Unauthorized" as the error message.

Default Error Handler

Slim provides a default HTTP error handler that uses Go's standard library function http.Error to respond to errors.

Default error handling example
500 Internal Server Error

The default error handler function is simple, does not expose excessive information, and ensures security in production environments.

Custom Error Handler

We can customize the HTTP error handler function through the instance property Slim#ErrorHandler.

In most cases, the default HTTP error handler is sufficient. However, if we want to capture different types of errors, then a custom HTTP error handler function can come in handy. We can freely take corresponding measures, such as sending notifications, emails, or logging errors, and can also send custom responses to clients, such as error pages or JSON data that aids debugging.

Error Pages

Here is an example of displaying different error types and logging errors through a custom HTTP error handler function:

Defining error pages
func customErrorHandler(c slim.Context, err error) {
code := http.StatusInternalServerError
if he, ok := err.(*slim.HTTPError); ok {
code = he.Code
}
fmt.Println(err)
errorPage := fmt.Sprintf("%d.html", code)
err2 = c.File(errorPage)
if err2 != nil {
fmt.Println(err2)
}
}

s.ErrorHandler = customErrorHandler
tip

In addition to writing logs to a logger, we can also write them to external services such as Elasticsearch or Splunk.