簡體   English   中英

SpringMVC:ExceptionHandler無法捕獲我的自定義異常

[英]SpringMVC: ExceptionHandler fails to catch my custom exception

在我的主控制器中 ,當拋出異常時,我希望它在我的錯誤處理控制器中ExceptionHandler捕獲,但這種情況從未發生過。 相反,我得到Error 500 我懷疑問題出在我的主控制器的@ResponseBody注釋中。 知道如何實現通緝行為嗎?

主控制器

@RequestMapping(value = "/person/{person}", method = RequestMethod.GET)
public @ResponseBody Person execute(@PathVariable(value = "person") String person) {

    if(person.isValid(person)) {
            return person;
    } else {
        throw new ResourceNotFoundException("Invalid person format.");
    }
}

例外

@ResponseStatus(value = HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {

    public ResourceNotFoundException() {
    }

    public ResourceNotFoundException(String message) {
        super(message);
    }

    public ResourceNotFoundException(String message, Throwable throwable) {
        super(message, throwable);
    }

    public ResourceNotFoundException(Throwable throwable) {
        super(throwable);
    }
}

錯誤控制器

private static final String ERROR_PAGE = "errors/error.jsp";

    @ResponseStatus(value = HttpStatus.NOT_FOUND)
    @ExceptionHandler(ResourceNotFoundException.class)
    public ModelAndView invalidApiCall(){
        return generateView(ERROR_404);
    }

    private ModelAndView generateView(String errorCode) {
        return new ModelAndView(ERROR_PAGE);

    }

永遠不會生成我的錯誤視圖(@ExceptionHandler永遠不會捕獲異常)。 相反,我得到錯誤500. ExceptionHandler是否有辦法捕獲我的異常?

嘗試為Error Controller添加@ControllerAdvice批注。 如果已添加,請檢查類包是否包含在包掃描中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM