java – Spring中的ExceptionHandler
import org.springframework.beans.TypeMismatchException; import javax.annotation.*; import javax.servlet.http.*; import org.springframework.http.HttpStatus; import org.springframework.stereotype.Controller; import org.springframework.context.annotation.Scope; import org.springframework.web.bind.annotation.*; @Controller @RequestMapping(value = "/aa") public class BaseController { @RequestMapping(value = "/bb/{number}",method = RequestMethod.GET,produces = "plain/text") public void test(@PathVariable final double number,final HttpServletResponse response) throws IOException { throw new MyException("whatever"); } @ResponseBody @ExceptionHandler(MyException.class) public MyError handleMyException(final MyException exception,final HttpServletResponse response) throws IOException { ... } @ResponseBody @ExceptionHandler(TypeMismatchException.class) public MyError handleTypeMismatchException(final TypeMismatchException exception,final HttpServletResponse response) throws IOException { ... } @ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR) @ResponseBody @ExceptionHandler public MyError handleException(final Exception exception) throws IOException { ... } } 如果我拨打http://example.com/aa/bb/20 但是,如果我拨打http://example.com/aa/bb/QQQ 一个令人讨厌的解决方法,就是在handleException()中测试异常的类型, 但为什么现在有效? 解决方法
摘自
official spring documentation:
在实际执行方法之前,您尝试捕获的异常是由spring本身(字符串到双重转换)生成的.捕获它不符合@ExceptionHandler的规范.这确实有意义 – 通常你不想捕获框架本身产生的异常. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |