i need to catch all exceptions of my controllers to a exception controller. How to configure spring?
I need this because every request to my webapp are json request and in case of exception i need to answer with a genericc {success: false, exception: "String ex..."}. But i can not understand if the better way is to use SimpleMappingExceptionResolver.
Thank you.
If you want to write a custom response, it would be more interesting to use a custom HandlerExceptionResolver implementation.
spring configuration:
<bean id="exceptionHandler" class="com.am.CustomHandlerExceptionResolver"/>
java:
public class CustomHandlerExceptionResolver
implements HandlerExceptionResolver {
#Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
//write in response
return null;
}
}
Related
My Spring Boot application uses OAuth2 for security and token management. I’m querying one of my REST endpoints with an invalid token to test its response using Postman. The endpoint is correctly responding with 401 InvalidTokenException but the response content is HTML when I would like it to respond with JSON. Can this be done via code?
Example response
<InvalidTokenException>
<error>invalid_token</error>
<error_description>Access token expired: … my token… </error_description>
</InvalidTokenException>
To elaborate on zfChaos's answer, which is a good lead but does not provide sufficient information for the response to be a JSON response:
You should also set the content type and character encoding.
Then, write your JSON response (in this example I used a simple String, of course it would be more convenient use a class and an ObjectMapper).
Here is a complete example:
#Configuration
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
#Override
public void configure(HttpSecurity httpSecurity) throws Exception {
httpSecurity
.oauth2Login(login -> login
.failureHandler((request, response, exception) -> {
response.setContentType("application/json");
response.setStatus(401);
response.setCharacterEncoding("UTF-8");
response.getWriter().write("{ \"msg\": \"foo\" }");
})
);
}
}
Add custom AuthenticationFailureHandler to your security configuration and then prepare response in your custom implementation:
http.oauth2Login()
.failureHandler(customFailureHandler)
Failure handler example:
public class CustomFailureHandler extends SimpleUrlAuthenticationFailureHandler {
#Override
public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException {
response.sendError(401, "XML HERE");
}
}
I have a rest web service developed with Spring Boot.I am able to handle all the exceptions that occur due to my code, but suppose the json object that the client posts is not compatible with the object that i want to desrialize it with, I get
"timestamp": 1498834369591,
"status": 400,
"error": "Bad Request",
"exception": "org.springframework.http.converter.HttpMessageNotReadableException",
"message": "JSON parse error: Can not deserialize value
I wanted to know is there a way that for this exception, I can provide the client a custom exception message. I am not sure how to handle this error.
To customize this message per Controller, use a combination of #ExceptionHandler and #ResponseStatus within your Controllers:
#ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "CUSTOM MESSAGE HERE")
#ExceptionHandler(HttpMessageNotReadableException.class)
public void handleException(HttpMessageNotReadableException ex) {
//Handle Exception Here...
}
If you'd rather define this once and handle these Exceptions globally, then use a #ControllerAdvice class:
#ControllerAdvice
public class CustomControllerAdvice {
#ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "CUSTOM MESSAGE HERE")
#ExceptionHandler(HttpMessageNotReadableException.class)
public void handleException(HttpMessageNotReadableException ex) {
//Handle Exception Here...
}
}
You also can extend ResponseEntityExceptionHandler and override the method handleHttpMessageNotReadable (example in Kotlin, but very similar in Java):
override fun handleHttpMessageNotReadable(ex: HttpMessageNotReadableException, headers: HttpHeaders, status: HttpStatus, request: WebRequest): ResponseEntity<Any> {
val entity = ErrorResponse(status, ex.message ?: ex.localizedMessage, request)
return this.handleExceptionInternal(ex, entity as Any?, headers, status, request)
}
I use this exception handler to handle some specific exceptions in my Spring boot application (REST API):
#ControllerAdvice
class GlobalExceptionHandler {
#ExceptionHandler(NotFoundException.class)
#ResponseStatus(HttpStatus.NOT_FOUND)
public
#ResponseBody
ResponseMessage notFound(NotFoundException ex) {
return new NotFoundResponseMessage(ex.getMessage());
}
#ResponseStatus(value = HttpStatus.UNSUPPORTED_MEDIA_TYPE)
#ExceptionHandler(HttpMediaTypeNotSupportedException.class)
public
#ResponseBody
ResponseMessage unsupportedMediaType(HttpMediaTypeNotSupportedException ex) {
return new UnsupportedMediaTypeResponseMessage(ex.getMessage());
}
#ExceptionHandler(UnauthorizedException.class)
#ResponseStatus(HttpStatus.UNAUTHORIZED)
public
#ResponseBody
ResponseMessage unauthorized(UnauthorizedException ex) {
return new UnauthorizedResponseMessage(ex.getMessage());
}
#ExceptionHandler(HttpRequestMethodNotSupportedException.class)
#ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
public
#ResponseBody
ResponseMessage methodNotAllowed(HttpRequestMethodNotSupportedException ex) {
return new MethodNotAllowedResponseMessage(ex.getMessage());
}
#ExceptionHandler(ForbiddenException.class)
#ResponseStatus(HttpStatus.FORBIDDEN)
public
#ResponseBody
ResponseMessage forbidden(ForbiddenException ex) {
return new ForbiddenResponseMessage(ex.getMessage());
}
}
and I would like to handle all the others exceptions with one "global" handling method. But I need to get HTTP status code in this method to process error message etc.
Question
Is there some way how to redirect all non-handled exceptions into one particular method? How can I do it?
See the docs:
Any Spring bean declared in the DispatcherServlet’s application
context that implements HandlerExceptionResolver will be used to
intercept and process any exception raised in the MVC system and not
handled by a Controller.
public interface HandlerExceptionResolver {
ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex);
}
I'm using Bean Validation with RestEasy in Wildfly 8.2.0.Final:
#Path("/user")
#Produces(MediaType.APPLICATION_JSON)
public class UserEndpoint
{
//more code
#GET
#Path("/encrypt/{email}")
public Response fetchEncryptedId(#PathParam("email") #NotNull String email)
{
String encryptedUserId = userService.getEncryptedUserId(email);
return Response.ok().entity(new UserBo(encryptedUserId)).build();
}
}
This basically works. Now I'd like to get the response as JSON object but I can't get it working. All my "application" exceptions are handled by my Exception Mapper, this works:
#Provider
public class DefaultExceptionMapper implements ExceptionMapper<Exception>
{
private static final String MEDIA_TYPE = "application/json";
private LoggingService loggingService;
#EJB
public void setLoggingService(LoggingService loggingService)
{
this.loggingService = loggingService;
}
#Override
public Response toResponse(Exception exception)
{
ResponseObject responseObject = new ResponseObject();
responseObject.registerExceptionMessage(exception.getMessage());
if (exception instanceof ForbiddenException)
{
loggingService.log(LogLevel.ERROR, ((ForbiddenException)exception).getUserId(), ExceptionToStringMapper.map(exception));
return Response.status(Status.FORBIDDEN).type(MEDIA_TYPE).entity(responseObject).build();
}
//more handling
loggingService.log(LogLevel.ERROR, "", ExceptionToStringMapper.map(exception));
return Response.status(Status.INTERNAL_SERVER_ERROR).type(MEDIA_TYPE).entity(responseObject).build();
}
}
But bean validation somehow bypasses it. Then I thought about using Throwable instead of Exception but it didn't help either. I guess the ExceptionMapper is not triggered because there is some life cycle problem with JAX-RS and JSR303. But how can I syncronize them to handle bean validation exceptions?
Additional information: The exception passes the javax.ws.rs.container.ContainerResponseFilter so I could write some workaround by implementing the filter method in a subclass, but this is not clean solution. The target is to handle the exceptions in the Exception mapper.
It's not always the case that your ExceptionMapper<Exception> will catch all exception under the Exception hierarchy. If there is another more specific mapper, say one for RuntimeException, that mapper will be used for all exception of RuntimeException and its subtypes.
That being said (assuming you're using resteasy-validation-provider-11), there is already a ResteasyViolationExceptionMapper that handles ValidationException.
#Provider
public class ResteasyViolationExceptionMapper
implements ExceptionMapper<ValidationException>
This mapper is automatically registered. It returns results in the form of a ViolationReport. The client needs to set the Accept header to application/json in order to see a response similar to
{
"exception":null,
"fieldViolations":[],
"propertyViolations":[],
"classViolations":[],
"parameterViolations":[
{
"constraintType":"PARAMETER",
"path":"get.arg0",
"message":"size must be between 2 and 2147483647",
"value":"1"}
],
"returnValueViolations":[]
}
You can see more at Violation reporting.
If you want to completely override this behavior, you can create a more specific mapper for ResteasyViolationException, which is the exception thrown by the RESTeasy validator
#Provider
public class MyValidationMapper
implements ExceptionMapper<ResteasyViolationException> {
#Override
public Response toResponse(ResteasyViolationException e) {
}
}
I have a Jersey application where I want to prevent the client from seeing any type of stacktrace if any type of Exception occurs.
How do I do this without changing any existing code?
You can register an exception mapper as follows to handle all exceptions and customize the HTTP response:
#Provider
public class MyExceptionMapper implements javax.ws.rs.ext.ExceptionMapper<Exception> {
#Override
public Response toResponse(Exception ex) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).build();
}
}