java @RestContollerAdvice未引发自定义异常

f45qwnt8  于 2023-02-14  发布在  Java
关注(0)|答案(2)|浏览(153)

我正在使用Sping Boot 3开发一个简单的Rest API,并希望使用@RestControllerAdvice处理异常,但我的代码抛出了500错误,即使@exceptionHandler中的代码抛出了404错误代码。我在调试中验证了执行到达了ExceptionHandler方法,但仍然抛出了默认异常。
下面是示例代码:

@RestControllerAdvice
public class ControllerExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(ResourceNotFoundException.class)
    @ResponseStatus(code = HttpStatus.NOT_FOUND)
    public Messsage resourceNotFoundException(ResourceNotFoundException exception, WebRequest request) {
        return new Messsage(HttpStatus.NOT_FOUND.value(), exception.getMessage(), LocalDateTime.now());
    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(code = HttpStatus.NOT_FOUND)
    public Messsage globalException(Exception exception, WebRequest request) {
        return new Messsage(HttpStatus.NOT_FOUND.value(), exception.getMessage(), LocalDateTime.now());
    }
}
pgky5nke

pgky5nke1#

很可能是在异常处理程序方法内部引发了另一个异常,从而导致500错误。若要解决此问题,可以向异常处理程序方法添加其他日志记录,以查看导致500错误的原因。最好在resourceNotFoundException和globalException方法中使用try和catch块。

tnkciper

tnkciper2#

尝试删除ResponseEntityExceptionHandler。其中一些exceptionHandler已经定义,它可能会捕捉异常之前,您自定义exceptionHandler。我做了一些单元测试,这里是代码样本;

  • 应用
@SpringBootApplication
public class AccountApplication {
    public static void main(String[] args) {
        SpringApplication.run(AccountApplication.class);
    }
}
  • 主计长
/**
 * @author pengpeng
 * @description
 * @date 2023/2/13
 */
@RequestMapping
@RestController
public class AccountController {

    @GetMapping("/test/{args}")
    public String testError(@PathVariable ("args") String args) throws IllegalAccessException {
        if (args .equals("ill")){
            throw new IllegalAccessException();

        } else if (args.equals("exception")) {
            throw new RuntimeException();
        }else {
            return "success";
        }
    }

}
  • 异常处理程序
/**
 * @author pengpeng
 * @description
 * @date 2023/2/13
 */
@RestControllerAdvice
public class ControllerException extends ResponseEntityResultHandler {

    public ControllerException(List<HttpMessageWriter<?>> writers, RequestedContentTypeResolver resolver) {
        super(writers, resolver);
    }

    public ControllerException(List<HttpMessageWriter<?>> writers, RequestedContentTypeResolver resolver, ReactiveAdapterRegistry registry) {
        super(writers, resolver, registry);
    }

    @ExceptionHandler
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public String illegalFail(IllegalAccessException exception){
        return "illegalFail";
    }


    @ExceptionHandler
    @ResponseStatus(HttpStatus.BAD_GATEWAY)
    public String fail(Exception exception){
        return "fail";
    }
}

应用程序启动后,使用默认应用程序端口启动HTTP调用

  • http
127.0.0.1/test/ill
127.0.0.1/test/exception
127.0.0.1/test/success

相关问题