SpringMVC Exception Handler

来源:互联网 发布:淘宝女装海报设计 编辑:程序博客网 时间:2024/06/14 10:18

1. Customize Exception

public class ArticleNotFoundException extends RuntimeException {    public ArticleNotFoundException(String message) {        super(message);    }}

2. Add exception handler method to Controller class

    Please note the exception handler method should be in the same class as the controller, which throws exception. And this kind of exception handler can only handle exception throws in this controller

@ExceptionHandler(ArticleNotFoundException.class)@ResponseStatus(HttpStatus.NOT_FOUND)public Error articleNotFound(ArticleNotFoundException exception) {    return new Error(exception.getMessage());}

3. Throw exception in controller method

@RequestMapping(value = Urls.REST + Urls.ARTICLE + Urls.NUMERICID, method = {GET}, produces = "application/json")public Article getArticle(@PathVariable("id") String id, HttpServletRequest request)        throws UnsupportedEncodingException {    Article article = null;    try {        request.setCharacterEncoding("UTF-8");        ArticleService articleService = new ArticleService();        article = articleService.getArticleById(id);    } catch(Exception e) {        throw new ServerInnerException(e.getMessage(), e);    }    if (article != null) {        return article;    }    throw new ArticleNotFoundException("Can't find the article");}

4. Create @ControllerAdvice class

    If you use this way, the exception handler method defined in this class, can handle exception thrown by all the controller class

@ControllerAdvicepublic class ErrorHandler {    @ExceptionHandler(ServerInnerException.class)    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)    public java.lang.Error innerServerError(ServerInnerException exception) {        return new java.lang.Error(exception.getMessage());    }    @ExceptionHandler(ArticleNotFoundException.class)    @ResponseStatus(HttpStatus.NOT_FOUND)    public Error articleNotFound(ArticleNotFoundException exception) {        return new Error(exception.getMessage());    }}