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()); }}
阅读全文
0 0
- SpringMVC Exception Handler
- springmvc-exception
- @valid在SpringMVC中报错[Handler processing failed; nested exception is java.lang.NoSuchFieldError:TRACE
- Exception handler interface
- Exception handler interface ' implementation
- JBPM知识点------exception-handler
- Handler替代Exception函数
- JBPM知识点------exception-handler
- spring-rest-exception-handler
- File Exception Handler
- springMVC自定义Exception
- springmvc exception的支持
- Provide an uncaught exception handler
- exception handler in drools rule
- laravel - Error in exception handler
- MySql Exception Handler的优先级
- Web api global Exception Handler
- SpringMVC 入门 -- Handler编写
- 优雅地使用Snackbar 简单封装
- 清晰weblog日志,过滤不合法的记录
- git公钥私钥定义
- codevs 1017 乘积最大
- oj Runtime error常见原因+cpp函数命名规则
- SpringMVC Exception Handler
- K路归并 例题
- TensorFlow学习笔记:2、TensorFlow超简单入门程序
- 中科院量子创新研究院联合阿里云发布量子计算云平台
- 15算法课程 100. Same Tree
- ubuntu rails连接mongodb十步实例教程
- 转录组分析的正确姿势
- 用虚拟机模拟vpn的实现
- 访问修饰符权限