DEV Community

Cover image for Handling our API errors
Marcos Filho
Marcos Filho

Posted on

Handling our API errors

All the codes that you will see in this post you can check here

In the last post, we build a DealWith() method to handle our API errors, but we do nothing at the moment. In this post we will build how to deliver a user-friendly way to show the user our problem. In case the problem is not a registered error (an error that we build and is a part of our application), we will centralize our error stack to share with the developer's team where the problem is (file, method name, and line) to the team solve the possible problem.

To represent our registered errors we will create a error map (errorHandlerMap) to store an error as a key and a http code as a value.


var (
    errorHandlerMap = make(map[error]int)

func DealWith(err error) HttpError {
    if errCode, ok := errorHandlerMap[err]; ok {
        return HttpError{Status: errCode, Description: err.Error()}
    } else {
        return HttpError{
            Status:      http.StatusInternalServerError,
            Description: "Internal error, please report to admin",

Enter fullscreen mode Exit fullscreen mode

Now you can see our DealWith method checks if our errorHandlerMap has an error key registered in our map. If the error that we want to deal with is registered, we will represent a specific Http Code with a specific message. Anything else will be designated as an unregistered error or an error that we don't know how to deal with at the moment.

This map will increase while we creating this app. Not every application error needs to be in this map, but if your error should be delivered with a user friendly message, then this error needs to be registered in this map with a specific http code.

If you see our code probably thinking that our map don't have any error registered, and you right. We will start to register some validations errors in the next post.

Oldest comments (0)