1

I'm very new to spring mvc sorry if I'm asking a basic questions, I need to maintain Global Exception Handling in my spring 4 MVC, Jersey project and return JSON response to IOS mobile app. Now by using @ControllerAdvice and @ExceptionHandler, I have created a class like below

@ControllerAdvice
public class GlobalExceptionHandlerController {

    @ExceptionHandler(Exception.class)
    public @ResponseBody handleException(HttpServletRequest reqException ex) {
            ErrorInfo response=new ErrorInfo();
                   if(ex.getMessage.contains("java.io")){
                     response.setMessage("FileNotFound exception occur");
                        return response;
                     }else if ...
    }

Please advice if above approach is correct or is there any alternative way to handle all exceptions occur in controller,service and DAO layer.

1
  • What exactly does this have to do with Jersey? I see a reference in your post to Jersey, but I don't see any other supporting details. Commented Jul 15, 2016 at 6:28

1 Answer 1

2

what you use is correct, all exceptions just be handled.In service or Dao layer,you just need to throw your business exception.The class you have created will catch the exception.But you should handle the exception in different ways,and define your own business exception. here are some example codes.

@ExceptionHandler(RuntimeException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public ErrorResponse handleUnexpectedServerError(RuntimeException ex) {
    ex.printStackTrace();
    return new ErrorResponse("012", ex.getMessage());
}

handle the business exception,the BusinessErrorException is custom exception.

@ExceptionHandler(BusinessErrorException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
@ResponseBody
public ErrorResponse handleBusinessErrorException(BusinessErrorExceptionex) {

    return new ErrorResponse(ex.getCode(), ex.getMessage());
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.