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
@Error
public HttpResponse<JsonError> jsonError(HttpRequest request, JsonParseException jsonParseException) { (1)
JsonError error = new JsonError("Invalid JSON: " + jsonParseException.getMessage()) (2)
.link(Link.SELF, Link.of(request.getUri()));
return HttpResponse.<JsonError>status(HttpStatus.BAD_REQUEST, "Fix Your JSON")
.body(error); (3)
}
Local exception handler
@Error
HttpResponse<JsonError> jsonError(HttpRequest request, JsonParseException jsonParseException) { (1)
JsonError error = new JsonError("Invalid JSON: " + jsonParseException.getMessage()) (2)
.link(Link.SELF, Link.of(request.getUri()))
HttpResponse.<JsonError>status(HttpStatus.BAD_REQUEST, "Fix Your JSON")
.body(error) (3)
}
Local exception handler
@Error
fun jsonError(request: HttpRequest<*>, jsonParseException: JsonParseException): HttpResponse<JsonError> { (1)
val error = JsonError("Invalid JSON: " + jsonParseException.message) (2)
.link(Link.SELF, Link.of(request.uri))
return HttpResponse.status<JsonError>(HttpStatus.BAD_REQUEST, "Fix Your JSON")
.body(error) (3)
}
1 | A method that explicitly handles JsonParseException is declared |
2 | An instance of JsonError is returned. |
3 | A custom response is returned to handle the error |
Local 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)
}
Local 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)
}
Local 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 |