6.17.3 Global Error Handling

Global error handler

  1. @Error(global = true) (1)
  2. public HttpResponse<JsonError> error(HttpRequest request, Throwable e) {
  3. JsonError error = new JsonError("Bad Things Happened: " + e.getMessage()) (2)
  4. .link(Link.SELF, Link.of(request.getUri()));
  5. return HttpResponse.<JsonError>serverError()
  6. .body(error); (3)
  7. }

Global error handler

  1. @Error(global = true) (1)
  2. HttpResponse<JsonError> error(HttpRequest request, Throwable e) {
  3. JsonError error = new JsonError("Bad Things Happened: " + e.message) (2)
  4. .link(Link.SELF, Link.of(request.uri))
  5. HttpResponse.<JsonError>serverError()
  6. .body(error) (3)
  7. }

Global error handler

  1. @Error(global = true) (1)
  2. fun error(request: HttpRequest<*>, e: Throwable): HttpResponse<JsonError> {
  3. val error = JsonError("Bad Things Happened: ${e.message}") (2)
  4. .link(Link.SELF, Link.of(request.uri))
  5. return HttpResponse.serverError<JsonError>()
  6. .body(error) (3)
  7. }
1The @Error declares the method a global error handler
2A JsonError instance is returned for all errors
3An INTERNAL_SERVER_ERROR response is returned

Global status handler

  1. @Error(status = HttpStatus.NOT_FOUND)
  2. public HttpResponse<JsonError> notFound(HttpRequest request) { (1)
  3. JsonError error = new JsonError("Person Not Found") (2)
  4. .link(Link.SELF, Link.of(request.getUri()));
  5. return HttpResponse.<JsonError>notFound()
  6. .body(error); (3)
  7. }

Global status handler

  1. @Error(status = HttpStatus.NOT_FOUND)
  2. HttpResponse<JsonError> notFound(HttpRequest request) { (1)
  3. JsonError error = new JsonError("Person Not Found") (2)
  4. .link(Link.SELF, Link.of(request.uri))
  5. HttpResponse.<JsonError>notFound()
  6. .body(error) (3)
  7. }

Global status handler

  1. @Error(status = HttpStatus.NOT_FOUND)
  2. fun notFound(request: HttpRequest<*>): HttpResponse<JsonError> { (1)
  3. val error = JsonError("Person Not Found") (2)
  4. .link(Link.SELF, Link.of(request.uri))
  5. return HttpResponse.notFound<JsonError>()
  6. .body(error) (3)
  7. }
1The @Error declares which HttpStatus error code to handle (in this case 404)
2A JsonError instance is returned for all 404 responses
3An NOT_FOUND response is returned
A few things to note about the @Error annotation. You cannot declare identical global @Error annotations. Identical non-global @Error annotations cannot be declared in the same controller. If an @Error annotation with the same parameter exists as global and another as local, the local one takes precedence.