Spring MVC Exception Handler - Tuong-Nguyen/Spring GitHub Wiki
Exception Handler
- Exception handler in spring MVC is use to control the exceptions in our code.
- To learn more about exception hanlder you can look at here
Using Exception Handler
Throw Exception:
- In your controller method:
@RequestMapping(value = "/user/profile/{id}", method = RequestMethod.GET)
public String getUserProfile(@ModelAttribute("account") Account account, @PathVariable("id") String id, Model model){
account = service.getUserProfile(id);
if(account == null || account.getId() == null)
throw new RuntimeException();
model.addAttribute("statuses", EnrollStatus.values());
return "account/userprofile";
}
- You can throw another exceptions such as:
NullPointerException, SQLException etc.
Exception Handler:
- In the controller class you declare an method to control exception with annotation
@ExceptionHandler
@ExceptionHandler(NullPointerException.class)
public String exceptionControl(){
return "exceptions/controllerExceptionHandler";
}
- In
@ExceptionHandler(NullPointerException.class) the NullPointerException.class is use to specify the method that will be calll when you throw an exception.
- You can you another exception class such as:
SQLException.class, DataAccessException.class, Exception.class, etc.
- Or you can declare an custom exception class by
RuntimeException base class:
public class HttpExceptionHanler extends RuntimeException {
private String errorCode;
private String errorMessage;
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMessage() {
return errorMessage;
}
public void setErrorMessage(String errorMessage) {
this.errorMessage = errorMessage;
}
public HttpExceptionHanler(String errorCode, String errorMessage) {
this.errorCode = errorCode;
this.errorMessage = errorMessage;
}
}
- If you want use global exception handle to handle an same exception form many controller you can declare an class that implement Spring MVC Exception Handle Abtract classes.
- When you declare an exception class you must mark that class is an Bean object.
@Component
public class GlobalException implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
ModelAndView view = new ModelAndView();
view.setViewName("exceptions/globalExceptionHandler");
return view;
}
}
- Or using
@ControllerAdvice annotation:
@ControllerAdvice
class GlobalException {
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void handleConflict() {
// Do something
}
}