Throw special http status code

Status code is done with the kind of the errors library, you can found the status code equivalence below:

var KindToStatusCodeHook = func(k Kind) int {
	return http.StatusInternalServerError
}

func (k Kind) ToStatusCode() int {
	switch k {
	case KindCanceled, KindDeadlineExceeded:
		return http.StatusRequestTimeout
	case KindUnknown:
		return http.StatusInternalServerError
	case KindInvalidArgument:
		return http.StatusBadRequest
	case KindNotFound:
		return http.StatusNotFound
	case KindAlreadyExists, KindAborted:
		return http.StatusConflict
	case KindPermissionDenied:
		return http.StatusForbidden
	case KindUnauthenticated:
		return http.StatusUnauthorized
	case KindResourceExhausted:
		return http.StatusForbidden
	case KindFailedPrecondition:
		return http.StatusPreconditionFailed
	case KindOutOfRange:
		return http.StatusBadRequest
	case KindUnimplemented:
		return http.StatusNotImplemented
	case KindInternal, KindDataLoss, KindNone:
		return http.StatusInternalServerError
	case KindUnavailable:
		return http.StatusServiceUnavailable
	}

	return KindToStatusCodeHook(k)
}

As you can see there is a hook in the error library to add custom translation according to the custom kind that you will have created.

To throw an error with a special HTTP status simply return an error with the kind you want.

return errors.NewWithKind(errors.KindPermissionDenied, "you don't have sufficient permissions")
// will return a 403 status code

Last updated