Skip to content

AmuzaTkts/jsonapi-errors

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

14 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

jsonapi-errors GoDoc Build Status Coverage Status Go ReportCard

This package provides error bindings based on the JSON API reference.

The package provides two main structs that you can use on your application, the Error and Bag structs. When returning errors from your API you should return a Bag containing one or more errors.

bag := NewBagWithError(502, "Oops =(")
jsonStr, _ := json.Marshal(bag)

The above code will return the following JSON structure:

{
  "errors": [
    {
      "detail": "Oops =(",
      "status": "502"
    }
  ],
  "status": "502"
}

Multiple errors

This package adds the possibility to add multiple errors with different status codes. The package will check for the range of the errors and will set the main status key to the lower bound of the error class.

Eg: If add an error 501 and 502, the main status key will be 500.

bag := NewBag()
bag.AddError(501, "Server Error 1")
bag.AddError(502, "Server Error 2")

jsonStr, _ := json.Marshal(bag)

Will return:

{
    "errors": [
        {
            "detail": "Server Error 1",
            "status": "501"
        },
        {
            "detail": "Server Error 2",
            "status": "502"
        }
    ],
    "status": "500"
}

It's also possible to have errors of different classes(400 and 500 for example), in this case the package will silently return 400 as the main status.

bag := NewBag()
bag.AddError(401, "Client Error 1")
bag.AddError(502, "Server Error 1")

jsonStr, _ := json.Marshal(bag)
{
    "errors": [
        {
            "detail": "Client Error 1",
            "status": "401"
        },
        {
            "detail": "Server Error 1",
            "status": "502"
        }
    ],
    "status": "400"
}

About

Go bindings based on the JSON API errors reference

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages