user2452494
user2452494

Reputation: 11

Spring 4 mvc global exception Handling

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.

Upvotes: 1

Views: 2646

Answers (1)

Demon Coldmist
Demon Coldmist

Reputation: 2670

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

Upvotes: 2

Related Questions