How to catch RESTEasy Bean Validation Errors? - java

I am developing a simple RESTFul service using JBoss-7.1 and RESTEasy.
I have a REST Service, called CustomerService as follows:
#Path(value="/customers")
#ValidateRequest
class CustomerService
{
#Path(value="/{id}")
#GET
#Produces(MediaType.APPLICATION_XML)
public Customer getCustomer(#PathParam("id") #Min(value=1) Integer id)
{
Customer customer = null;
try {
customer = dao.getCustomer(id);
} catch (Exception e) {
e.printStackTrace();
}
return customer;
}
}
Here when I hit the url http://localhost:8080/SomeApp/customers/-1 then #Min constraint will fail and showing the stacktrace on the screen.
Is there a way to catch these validation errors so that I can prepare an xml response with proper error message and show to user?

You should use exception mapper. Example:
#Provider
public class ValidationExceptionMapper implements ExceptionMapper<javax.validation.ConstraintViolationException> {
public Response toResponse(javax.validation.ConstraintViolationException cex) {
Error error = new Error();
error.setMessage("Whatever message you want to send to user. " + cex);
return Response.entity(error).status(400).build(); //400 - bad request seems to be good choice
}
}
where Error could be something like:
#XmlRootElement
public class Error{
private String message;
//getter and setter for message field
}
Then you'll get error message wrapped into XML.

Related

What's the best option/alternative to treat exceptions in spring boot?

Right now i'm using this example of exception handling:
//get an object of type curse by id
//in the service file, this findCurseById() method throws a
//CursaNotFoundException
#GetMapping("/{id}")
public ResponseEntity<curse> getCursaById (#PathVariable("id") Long id) {
curse c = curseService.findCurseById(id);
return new ResponseEntity<>(c, HttpStatus.OK);
}
//so if not found, this will return the message of the error
#ResponseStatus(HttpStatus.NOT_FOUND)
#ExceptionHandler(CursaNotFoundException.class)
public String noCursaFound(CursaNotFoundException ex) {
return ex.getMessage();
}
and that's my exception
public class CursaNotFoundException extends RuntimeException {
public CursaNotFoundException(String s) {
super(s);
}
}
in future I want to use Angular as front-end, so I don't really know how I should treat the exceptions in the back-end. For this example let's say, should I redirect the page to a template.html page in the noCursaFound() method, or should I return something else? A json or something? I couldn't find anything helpful. Thanks
I would suggest keeping the error handling at the REST API level and not redirecting to another HTML page on the server side. Angular client application consumes the API response and redirects to template.html if needed.
Also, it would be better if the backend returns an ApiError when an exception occurs with a message and, optionally, an error code:
public class ApiError {
private String message;
private String code;
}
and handle the exceptions in a separate class, ExceptionHandler annotated with #ControllerAdvice:
#ControllerAdvice
public class ExceptionHandler {
#ExceptionHandler(value = CursaNotFoundException.class)
public ResponseEntity cursaNotFoundException(CursaNotFoundException cursaNotFoundException) {
ApiError error = new ApiError();
error.setMessase(cursaNotFoundException.getMessage());
error.setCode(cursaNotFoundException.getCode());
return new ResponseEntity(error, HttpStatus.NOT_FOUND);
}
#ExceptionHandler(value = Exception.class)
public ResponseEntity<> genericException(Exception exception) {
ApiError error = new ApiError();
error.setMessase(exception.getMessage());
error.setCode("GENERIC_ERROR");
return new ResponseEntity<>(error, HttpStatus.INTERNAL_SERVER_ERROR);
}
}

3 tiers architecture best practice using Spring Boot

I work with 3-tier architecture in a Spring Boot app. I created 3 packages (model, service, controller), but what I did, service calls a repo function with try catch, and then I call it in controller
Example:
Service:
public ResponseEntity<List<Customer>> getAllCustomers() {
try {
List<Customer> customers = new ArrayList<Customer>();
cutomerRepository.findAll().forEach(customers::add);
if (customers.isEmpty()) {
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<>(customers, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
Controller
#GetMapping("/viewList")
private ResponseEntity<?> getAllCustomers()
{
try{
return customerService.getAllCustomers();
}catch (Exception exception){
return new ResponseEntity<String>("Customers is not found", HttpStatus.METHOD_FAILURE);
}
}
Is that correct? I think I should put in services only customerRepository.findAll() without any other logic or code, but I'm not sure. Any idea?
The Service layer should contain logic, so that is OK.
But it should not contain any classes from the Controller layer, as this would leak information from an "upper" layer into a "lower" layer. This means your Service should not return a ResponseEntity as this is from the Controller layer. Instead it should return simply a list of Customers and let the Controller construct the ResponseEntity out of it.
Otherwise your Service will always be limited to be called by this specific Controller. It would not be reusable to be called by another service of a different type of Controller, that does not use an HTTP ResponseEntity.
The best approach in my opinion is the following.
Your Service layer should not return ResponseEntity<List<Customer>> as it currently does. It should instead return List<Customer>.
This is already in the above answer but wanted to answer to extend the content a bit more.
The service also when modified to return List<Customer> should handle the exceptions with Application specific exceptions. So you create your own exception for your application, the model for this exception and also you create an Exception Advice class where all those application exceptions are handled in a general way. So your service will just throw the exception, the controller will not catch it and it will be handled by the Advice class (annotated with #ControllerAdvice) which will handle all the uncaught exceptions and return appropriate responses. There are also some more options to handle exceptions in generic way in Spring.
I am attaching the following code as an example
Class to handle all exceptions that bubble up from controllers.
#ControllerAdvice
public class ErrorHandler {
#ExceptionHandler(ApplicationException.class)
public ResponseEntity handleApplicationException(ApplicationException e) {
return ResponseEntity.status(e.getCustomError().getCode()).body(e.getCustomError());
}
}
Some application specific exception (The name could be more specific)
#Getter
#Setter
public class ApplicationException extends RuntimeException {
private CustomError customError;
public ApplicationException(CustomError customError){
super();
this.customError = customError;
}
}
An Error object to be returned to the client when exception happens
#Getter
#Setter
#NoArgsConstructor
public class CustomError {
private int code;
private String message;
private String cause;
public CustomError(int code, String message, String cause) {
this.code = code;
this.message = message;
this.cause = cause;
}
#Override
public String toString() {
return "CustomError{" +
"code=" + code +
", message='" + message + '\'' +
", cause='" + cause + '\'' +
'}';
}
}
Your Service
public List<Customer> getAllCustomers() {
try {
List<Customer> customers = new ArrayList<Customer>();
cutomerRepository.findAll().forEach(customers::add);
if (customers.isEmpty()) {
throw new ApplicationException(new CustomError(204, "No Content", "Customers do not exist"));
}
return new ResponseEntity<>(customers, HttpStatus.OK);
} catch (Exception e) {
throw new ApplicationException(new CustomError(500, "Server Error", "Disclose to the client or not what the cause of the error in the server was"));
}
}
The controller it self could also inspect the input information that it receives and if needed could throw it self an application specific exception or just return an appropriate response with what is false in the input.
This way the Controller is just handling the input/output between the user and the service layer.
The Service is just handling input/output of data from persistent layer.

Spring MVC error handling with response status code

help me anybody Please in this issue.
The project, I am working on is old mvc, and is not going to be change to rest, So have to deal with "what we have :) ".
this is my controller method, the class of which is anotated #Controller
#RequestMapping(method=RequestMethod.POST)
public String createSomething(#RequestBody somejson, Model m) throws Exception {
SomeCustomListenerClass listener = new SomeCustomListenerClass(m);
AnnotherClass ac = somejson.toNotification(someService, anotherService, listener);
try {
ac = someService.createSomething(ac, listener);
m.addAttribute("success", true);
m.addAttribute("notificationId", ac.getId());
}
catch(SawtoothException ex) {
return handleError(ex, "Create Notification", listener);
}
return "structured";
}
and this one is handleError method body
private String handleError(Exception ex, String operation, SomeCustomListenerClass listener) {
if (!listener.hasErrors()) {
log.error("Unexpected error getting notification detail", ex);
listener.error("notification.controllerException", operation);
}
return "error";
}
Now I am getting the right errors in the client side, say in browser, but also getting the status code 500
now my boss says that we have to get 400, when validation errors hapens, not 500, as is now.
So, Please help me guys, how to overcome to this problem.
You can extend your exceptions and throw them on your controller:
#ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Your exception message")
public class YourCustomException extends RuntimeException {
}
Or you can use an ExceptionControllerHandler:
#Controller
public class ExceptionHandlingController {
// #RequestHandler methods
...
// Exception handling methods
// Convert a predefined exception to an HTTP Status code
#ResponseStatus(value=HttpStatus.CONFLICT,
reason="Data integrity violation") // 409
#ExceptionHandler(DataIntegrityViolationException.class)
public void conflict() {
// Nothing to do
}
// Specify name of a specific view that will be used to display the error:
#ExceptionHandler({SQLException.class,DataAccessException.class})
public String databaseError() {
// Nothing to do. Returns the logical view name of an error page, passed
// to the view-resolver(s) in usual way.
// Note that the exception is NOT available to this view (it is not added
// to the model) but see "Extending ExceptionHandlerExceptionResolver"
// below.
return "databaseError";
}
// Total control - setup a model and return the view name yourself. Or
// consider subclassing ExceptionHandlerExceptionResolver (see below).
#ExceptionHandler(Exception.class)
public ModelAndView handleError(HttpServletRequest req, Exception ex) {
logger.error("Request: " + req.getRequestURL() + " raised " + ex);
ModelAndView mav = new ModelAndView();
mav.addObject("exception", ex);
mav.addObject("url", req.getRequestURL());
mav.setViewName("error");
return mav;
}
}
Try the #ExceptionHandler annotation or #ControllerAdvice to create custom exception handling mechanisms:
https://www.tutorialspoint.com/spring_boot/spring_boot_exception_handling.htm
add #ResponseStatus(HttpStatus.BAD_REQUEST) on top of handleError(...) method.
#ExceptionHandler({ Throwable.class })
#ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleError(...) {
...
}

Is it possible to response with http error, that code are variable in java spring?

I have an Microservice and it gets an response from another. And based on the response I get I need to respond accordingly. I have no complete List of Error code I can receive, so the question is - can I generate error codes on the fly for my own response? From what I saw in spring the responses are predefined in code. I need to be flexible.
For example:
I receive a 409 I will respond with 409
I receive a 400 I will respond with 400
I receive a XXX code I will respond with XXX.
Try this code: (Sample code)
#RequestMapping(value = "/validate", method = RequestMethod.GET, produces = "application/json")
public ResponseEntity<ErrorBean> validateUser(#QueryParam("jsonInput") final String jsonInput) {
int numberHTTPDesired = 400;
ErrorBean responseBean = new ErrorBean();
responseBean.setError("ERROR");
responseBean.setMessage("Error in validation!");
return new ResponseEntity<ErrorBean>(responseBean, HttpStatus.valueOf(numberHTTPDesired));
}
I have worked on such a use case using the following concept. Try to create a generic exception across micro services. Take 2 params in the exception as error message and another one as error code. Throw the exception from the service being called and catch the same exception in the calling service in the rest template or feign client call.
public class MyException extends Exception {
private String errorCode;
public MyException() {
super();
}
public MyException(String message, String errorCode) {
super(message);
this.errorCode = errorCode;
}
}
--
try {
return myApiService.getUser();//call to myApiService microservice
} catch (MyException e) {
logger.error("Error: {}", e.getMessage());
throw new MyException(e.getMessage(), e.getCode());
}

Jersey custom ExceptionMapper not used if exception occurs when processing request body

I'm facing a tricky behavior from my REST resource.
The exposed method is expecting a complex json object :
#Path(RestURIConstant.NOTIFICATION_ROOT_URI)
#Component
#Scope("request")
public class NotificationResource implements RestURIConstant {
/** Notification service. */
#Autowired
private INotificationService notificationService;
#Path(RestURIConstant.COMPLEMENT_URI)
#POST
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public Response processNotification(final EventDTO event)
throws BusinessException, TechnicalException {
checkParameters(event);
notificationService.processEvent(event);
return Response.ok().build();
}
}
EventDTO has two enum fields : notificationType and eventType :
public class EventDTO {
private ENotificationType notificationType;
private EEventType eventType;
private String eventDate;
private String userName;
//... getters, setters
}
What I want is to map exception from any kind of data validation error to get at the end a json response with an error code and error message. And after following jax-rs jersey: Exception Mapping for Enum bound FormParam :
So for the ENoticationType I wrote :
public enum ENotificationEventType {
RULE,
ALARM,
ACK,
INFO;
#JsonCreator
public static ENotificationEventType fromString(final String typeCode)
throws BusinessException {
if (typeCode == null) {
throw new BusinessException(ValidationCode.VALUE_REQUIRED, "type");
}
try {
return valueOf(typeCode);
} catch (final IllegalArgumentException iae) {
throw new BusinessException(ValidationCode.UNSUPPORTED_VALUE, "type", typeCode, Arrays.toString(values()));
}
}
}
And for the Mapper I wrote :
#Provider
#Singleton
public class BusinessExceptionMapper implements ExceptionMapper<BusinessException> {
#Override
public Response toResponse(final BusinessException exception) {
Status status = Status.INTERNAL_SERVER_ERROR;
// If a validationCode error = unsupported version => CODE 410
if (exception.getErrorCode().equals(ValidationCode.UNSUPPORTED_API_VERSION)) {
status = Status.GONE;
} else if (exception.getErrorCode().getClass().isAssignableFrom(ValidationCode.class)) {
// If a validationCode error then BAD_REQUEST (400) HTTP
status = Status.BAD_REQUEST;
} else if (exception.getErrorCode().getClass().isAssignableFrom(NotFoundCode.class)) { // CODE 404
status = Status.NOT_FOUND;
} else if (exception.getErrorCode().getClass().isAssignableFrom(SecurityCode.class)) { // CODE 401
status = Status.UNAUTHORIZED;
} else if (exception.getErrorCode().getClass().isAssignableFrom(AdminSecurityCode.class)) { // CODE 401
status = Status.UNAUTHORIZED;
}
return Response.status(status).type(MediaType.APPLICATION_JSON)
.entity(ErrorMessageHelper.createErrorMessageHelper(
exception.getErrorCode(), exception.getMessage()))
.build();
}
And my application-context contains <context:component-scan base-package=" com.technicolor.hovis.backend.rest, com.technicolor.hovis.admin.rest" />
I already read several answers to questions relative to Exception mapping in jersey but in my case, it's not that the mapping is not recognized but that it's not applied in all cases :
the exceptions thrown by checkParameters are mapped and the result is as expected
but if an invalid enum is sent, the #JsonCreator method is called, throw the same type of exception but this one is not mapped as expected.
So The response looks like :
<data contentType="text/plain;charset=UTF-8" contentLength="176">
<![CDATA[Unsupported type value : 'ALARN'. Expected values are [RULE, ALARM, ACK, INFO] (through reference chain: EventDTO["type"])]]>
</data>
And not the expected :
{
"code": 6,
"message": "Unsupported type value : 'ALARN'. Expected values are [RULE, ALARM, ACK, INFO]"
}
Any idea ?
Cyril
I would try changing the BusinessExceptionMapper to:
public class BusinessExceptionMapper implements ExceptionMapper<Exception>
If I understand correctly, the problem is when deserializng the parameter you except, in that case an IOException will be thrown and not BusinessException which I am guessing is your custom notification. So you can either extend ExceptionMapper<Exception> or ExceptionMapper<IOException>
I noticed that when I throw a checked exception in JSONCreator (just like you did), Jackson catches it and wraps it in IllegalArgumentException, so IllegalArgumentException ends up in ExceptionMapper.
Maybe this was cause of your problems?

Categories

Resources