Error Handling in Jersey - exception

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();
}
}

Related

EJB wraps my customExceptions throwed from interceptors

I'm studying interceptors and decorator and when experimenting with it I've encountered the problem that if I throw a checked exception from an interceptor, the EJBContainer wraps it as an EJBException, instead what I would like to show to the client is my custom exception.
Assume that I've one simple method and one interceptor that check if the parameters are valid like so:
#Interceptor
public class TestIntercepor {
#AroundInvoke
public Object test(InvocationContext invCtx) throws Exception{
try {
//check parameters...
return invCtx.proceed();
} catch (CustomException ex) {
throw new CustomException();
} catch (Exception ex) {
throw new Exception();
}
}
}
The exception that I want to throw if something's off is CustomException:
public class CustomException extends Exception {
public CustomException() {
super("ERROR! Input fields not valid");
}
}
now I've noticed in my SOAP Fault message that the exception throwed is an EJBException. I did some research and found out that the EJB Container wraps all the SystemException throwed, so I'm assuming that my CustomException throwed by the interceptor is treated as an uncecked exception for some reason, while if I throw the same exception from the business method, the client see exactly the right exception in the message.
I've even tryed to add the #ApplicationException annotation in my CustomException class for be completely sure that my Exception has to be treated as an ApplicationException instead of a SystemException, but it doesn't seem to be working.
There's something I'm missing?
I've found out that if your custom exception extends RuntimeException instead of Exception it works. Seems like that the #ApplicationException work only if the exception is a System Exception like RuntimeException and not if extends normal Exception.
#ApplicationException(rollback = true)
public class CustomException extends RuntimeException {
public CustomException() {
super("ERROR! Input fields not valid");
}
}

Is it possible to configure OAuth2 in Spring Boot to respond with JSON instead of HTML for InvalidTokenException?

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");
}
}

How to handle all not handled exceptions in #ControllerAdvice?

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);
}

Wildfly: ExceptionMapper not triggered with RestEasy JSR-303 Bean Validation

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) {
}
}

Spring error handling

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;
}
}