> For the complete documentation index, see [llms.txt](https://alexisvisco.gitbook.io/kcd/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alexisvisco.gitbook.io/kcd/output/errors.md).

# Errors

### The error library

KCD comes with a great opinionated library that allows throwing error with status code translation, metadata, stack trace, logger ...&#x20;

This error library provided with kcd allows us to:

* Wrap errors
* Known the previous domain calls if we use wrap correctly across our codebase
* Attach a kind to the error (allow us to then translate the kind into HTTP status code)
* Add metadata (i.e. fields)
* Convert the error to logrus entry with stack trace ...
* Print beautifully into the stack trace

### Example

Default behavior:

```go
package main

import (
   "net/http"

   "github.com/go-chi/chi"
   
   "github.com/alexisvisco/pkg/errors"
   "github.com/alexisvisco/kcd"
)

func main() {
   r := chi.NewRouter()
   r.Post("/", kcd.Handler(YourHttpHandler, http.StatusOK))
   _ = http.ListenAndServe(":3000", r)
}



func YourHttpHandler() error {
   return errors.NewWithKind(errors.KindInternal, "this is an error")
}

// Test it : curl -XPOST 'localhost:3000'
```

if you throw this statement in your KCD handler you can expect the response below\...

```
{
  "error_description": "this is an error",
  "error": "internal"
}
```

And a log that looks like this in your console:

```
┌─────────────────────────────────────────────
│ DEBUG ERROR: "this is an error"
│  at main.go:21 main.YourHttpHandler <- error happened here

ERRO[0143]  error="this is an error" method=POST params= remote="127.0.0.1:51004" request=/ stacktrace="main/main.go.YourHttpHandler:21
```

Note that if the error is not an internal server error or an unknown error, the logger will not appear. \
If the logrus level is not in debug mode, the first stacktrace will not appear.

You can see the error handling in the [error hook](https://github.com/expectedsh/kcd/blob/master/pkg/hook/error.go) and the error logs in the [log hook](https://github.com/expectedsh/kcd/blob/master/pkg/hook/log.go).

### Format of the error message

The format of an error in KCD is the one that follows:

```
type ErrorResponse struct {
	ErrorDescription string      `json:"error_description"`
	Error            errors.Kind `json:"error"`

	Fields   map[string]string      `json:"fields,omitempty"`
	Metadata map[string]interface{} `json:"metadata,omitempty"`
}
```

* `error_description` the human-readable description of the error (your error message)
* `error` the error type (internal, invalid argument, forbidden, unauthorized ...)
* `fields` if there is a validation error, it will set the key with the field name and the value with the message error for this field
* `metadata` currently only used to put the request-id if mentioned
