-
Notifications
You must be signed in to change notification settings - Fork 0
Spring MVC Exception Handler
trongtao edited this page May 25, 2017
·
7 revisions
- 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
- 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,SQLExceptionetc.
- 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)theNullPointerException.classis 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
RuntimeExceptionbase 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
@ControllerAdviceannotation:
@ControllerAdvice
class GlobalException {
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(DataIntegrityViolationException.class)
public void handleConflict() {
// Do something
}
}