spring 自定义java Sping Boot 中的全局异常处理程序

pzfprimi  于 2022-10-30  发布在  Spring
关注(0)|答案(1)|浏览(146)

我的全局异常处理程序

@ControllerAdvice("uz.pdp.warehouse")
public class GlobalExceptionHandler {

    @ExceptionHandler({RuntimeException.class})
    public ResponseEntity<DataDto<AppError>> handle500(RuntimeException e, WebRequest webRequest) {
        return new ResponseEntity<>(
                new DataDto<>(AppErrorDto.builder()
                        .message(e.getMessage())
                        .status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .path(webRequest.getContextPath())
                        .build()));
    }

}

我想返回我的自定义ResponseEntity,但它返回了不同的内容

{
"timestamp": "2022-03-27T06:21:00.845+00:00",`
"status": 404,
"error": "Not Found",
"trace": "uz.pdp.warehouse.exception.NotFoundException: QWE\r\n",
"message": "QWE",
"path": "/test/testN"
}

然后,我还捕获了try{}catch(){}异常,它正在工作,但我希望通过我的GlobalExceptionHandler处理异常。

so what can I do?

是否可以返回自定义的AppErrorResposeEntity

qxgroojn

qxgroojn1#

您可能需要扩展ResponseEntityExceptionHandler,如下所示:

@ControllerAdvice("uz.pdp.warehouse")
public class GlobalExceptionHandler extends ResponseEntityExceptionHandler  {

    @ExceptionHandler({RuntimeException.class})
    public ResponseEntity<DataDto<AppError>> handle500(RuntimeException e, WebRequest webRequest) {
        return new ResponseEntity<>(
                new DataDto<>(AppErrorDto.builder()
                        .message(e.getMessage())
                        .status(HttpStatus.INTERNAL_SERVER_ERROR)
                        .path(webRequest.getContextPath())
                        .build()));
    }

}

相关问题