加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – Spring中的ExceptionHandler

发布时间:2020-12-14 19:33:03 所属栏目:Java 来源:网络整理
导读: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.ann
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
按预期执行函数handleMyException.

但是,如果我拨打http://example.com/aa/bb/QQQ
我希望调用函数handleTypeMismatchException,
但是,调用handleException,类型为TypeMismatchException.

一个令人讨厌的解决方法,就是在handleException()中测试异常的类型,
如果异常类型为TypeMismatchException,则调用handleTypeMismatchException.

但为什么现在有效?
根据异常的类型在运行时选择exceptionhandler?
还是在编译时选择?

解决方法

摘自 official spring documentation:

You use the @ExceptionHandler method annotation within a controller to
specify which method is invoked when an exception of a specific type
is thrown during the execution of controller methods

在实际执行方法之前,您尝试捕获的异常是由spring本身(字符串到双重转换)生成的.捕获它不符合@ExceptionHandler的规范.这确实有意义 – 通常你不想捕获框架本身产生的异常.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读