gpt4 book ai didi

java - SpringMVC : ExceptionHandler fails to catch my custom exception

转载 作者:行者123 更新时间:2023-11-29 04:35:04 25 4
gpt4 key购买 nike

在我的主 Controller 中,当抛出异常时,我希望它被我的错误处理 Controller 中的ExceptionHandler捕获,但那永远不会发生。相反,我收到了 Error 500。我怀疑问题出在我的主 Controller 的 @ResponseBody 注释中。知道如何实现所需的行为吗?

主 Controller

@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);
}
}

错误 Controller

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);

}

我的错误 View 永远不会生成(@ExceptionHandler 永远不会捕获异常)。相反,我收到错误 500。ExceptionHandler 是否有办法捕获我的异常?

最佳答案

尝试为错误 Controller 添加 @ControllerAdvice 注解。如果已经添加,请检查该类的包是否包含在包扫描中。

关于java - SpringMVC : ExceptionHandler fails to catch my custom exception,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41951942/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com