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,但 type 除外TypeMismatchException
。
一个讨厌的解决方法是测试内部异常的类型,如果异常是类型则handleException()
调用。handleTypeMismatchException
TypeMismatchException
但为什么它现在起作用了?根据异常类型在运行时选择异常处理程序?还是在编译时选择?