SpringMVC Exception Handler

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

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




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值