Local Error Handling

For example the following method will handling JSON parse exceptions from Jackson for the scope of the declaring controller:

Local exception handler

  1. @Error
  2. public HttpResponse<JsonError> jsonError(HttpRequest request, JsonParseException jsonParseException) { (1)
  3. JsonError error = new JsonError("Invalid JSON: " + jsonParseException.getMessage()) (2)
  4. .link(Link.SELF, Link.of(request.getUri()));
  5. return HttpResponse.<JsonError>status(HttpStatus.BAD_REQUEST, "Fix Your JSON")
  6. .body(error); (3)
  7. }

Local exception handler

  1. @Error
  2. HttpResponse<JsonError> jsonError(HttpRequest request, JsonParseException jsonParseException) { (1)
  3. JsonError error = new JsonError("Invalid JSON: " + jsonParseException.getMessage()) (2)
  4. .link(Link.SELF, Link.of(request.getUri()))
  5. HttpResponse.<JsonError>status(HttpStatus.BAD_REQUEST, "Fix Your JSON")
  6. .body(error) (3)
  7. }

Local exception handler

  1. @Error
  2. fun jsonError(request: HttpRequest<*>, jsonParseException: JsonParseException): HttpResponse<JsonError> { (1)
  3. val error = JsonError("Invalid JSON: " + jsonParseException.message) (2)
  4. .link(Link.SELF, Link.of(request.uri))
  5. return HttpResponse.status<JsonError>(HttpStatus.BAD_REQUEST, "Fix Your JSON")
  6. .body(error) (3)
  7. }
1A method that explicitly handles JsonParseException is declared
2An instance of JsonError is returned.
3A custom response is returned to handle the error

Local 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. }

Local 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.getUri()))
  5. HttpResponse.<JsonError>notFound()
  6. .body(error) (3)
  7. }

Local 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