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按預期執行。Spring中的ExceptionHandler
但是,如果我叫http://example.com/aa/bb/QQQ 我期望的功能handleTypeMismatchException
被調用, 而是handleException被調用,以TypeMismatchException
類型的異常。
一個討厭的解決辦法,使這將是測試異常的類型裏面handleException()
, 並調用handleTypeMismatchException
如果異常是TypeMismatchException
類型。
但它爲什麼現在可以工作? 異常處理程序是根據異常的類型在運行時選擇的? 或在編譯時選擇?
在http:// example.com/aa/bb/QQQ的情況下引發的異常是什麼? –
函數handleException(final異常異常)被調用,異常是TypeMismatchException的一個實例。 –