java – Spring中的ExceptionHandler

前端之家收集整理的这篇文章主要介绍了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
按预期执行函数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的规范.这确实有意义 – 通常你不想捕获框架本身产生的异常.

猜你在找的Java相关文章