Global Error Handling
Global error handler
@Error(global = true) (1)
public HttpResponse<JsonError> error(HttpRequest request, Throwable e) {
JsonError error = new JsonError("Bad Things Happened: " + e.getMessage()) (2)
.link(Link.SELF, Link.of(request.getUri()));
return HttpResponse.<JsonError>serverError()
.body(error); (3)
}
Global error handler
@Error(global = true) (1)
HttpResponse<JsonError> error(HttpRequest request, Throwable e) {
JsonError error = new JsonError("Bad Things Happened: " + e.getMessage()) (2)
.link(Link.SELF, Link.of(request.getUri()))
HttpResponse.<JsonError>serverError()
.body(error) (3)
}
Global error handler
@Error(global = true) (1)
fun error(request: HttpRequest<*>, e: Throwable): HttpResponse<JsonError> {
val error = JsonError("Bad Things Happened: " + e.message) (2)
.link(Link.SELF, Link.of(request.uri))
return HttpResponse.serverError<JsonError>()
.body(error) (3)
}
1 | The Error is used to declare the method a global error handler |
2 | A JsonError instance is returned for all errors |
3 | An INTERNAL_SERVER_ERROR response is returned |
Global status handler
@Error(status = HttpStatus.NOT_FOUND)
public HttpResponse<JsonError> notFound(HttpRequest request) { (1)
JsonError error = new JsonError("Person Not Found") (2)
.link(Link.SELF, Link.of(request.getUri()));
return HttpResponse.<JsonError>notFound()
.body(error); (3)
}
Global status handler
@Error(status = HttpStatus.NOT_FOUND)
HttpResponse<JsonError> notFound(HttpRequest request) { (1)
JsonError error = new JsonError("Person Not Found") (2)
.link(Link.SELF, Link.of(request.getUri()))
HttpResponse.<JsonError>notFound()
.body(error) (3)
}
Global status handler
@Error(status = HttpStatus.NOT_FOUND)
fun notFound(request: HttpRequest<*>): HttpResponse<JsonError> { (1)
val error = JsonError("Person Not Found") (2)
.link(Link.SELF, Link.of(request.uri))
return HttpResponse.notFound<JsonError>()
.body(error) (3)
}
1 | The Error declares which HttpStatus error code to handle (in this case 404) |
2 | A JsonError instance is returned for all 404 responses |
3 | An NOT_FOUND response is returned |
A few things to note about the Error annotation. Two identical @Error annotations that are global cannot be declared. Two identical @Error annotations that are non-global cannot be declared in the same controller. If an @Error annotation with the same parameter exists as global and another as a local, the local one will take precedence. |