说起统一异常处理,后端开发中其实有非常成熟的模式——@ControllerAdvice配合@ExceptionHandler,再搭配一个自定义的ErrorResponse实体,就能优雅地搞定。这套方案的好处在于,它让错误响应变得结构清晰,前端调用方拿到后一目了然,不用再费劲解析各种乱七八糟的异常格式。

Ja va中 统一异常处理返回结构怎么包含 timestamp, path, error, status

在Spring Boot中,要实现带有timestamppatherrorstatus这几个字段的响应结构,推荐直接上@ControllerAdvice + @ExceptionHandler,配合自定义的响应体。

定义标准化响应实体

先创建一个通用的响应类,比如就叫ErrorResponse,把异常时需要返回的核心字段封装进去:

编写全局异常处理器

@ControllerAdvice来捕获所有控制器抛出的异常,然后构造ErrorResponse返回:

@ControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public ResponseEntity handleGenericException(
            Exception ex, WebRequest request) {

        HttpStatus status = (ex instanceof HttpClientErrorException) 
                ? ((HttpClientErrorException) ex).getStatusCode() 
                : HttpStatus.INTERNAL_SERVER_ERROR;

        ErrorResponse errorResponse = new ErrorResponse(
                Instant.now(),
                request.getDescription(false), // 默认带uri=xxx,需要纯净path的话可以注入HttpServletRequest
                status.getReasonPhrase(),
                status.value()
        );

        return ResponseEntity.status(status).body(errorResponse);
    }
}

这里有个小细节:request.getDescription(false)返回的是"uri=xxx"这种格式,如果想拿到干净纯粹的path,建议直接注入HttpServletRequest,调用getServletPath()getRequestURI()

补充常见异常的精细化处理

针对不同异常类型,返回更精准的状态码和错误信息,效果会更好:

确保响应体序列化友好

ErrorResponse类里,加上Lombok注解或者手动写getter/setter,再用@JsonFormat规范一下时间格式:

public class ErrorResponse {
    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss.SSS")
    private Instant timestamp;
    private String path;
    private String error;
    private int status;

    // 构造方法、getter、setter...
}

这样最终返回的JSON就是标准格式,比如:

{ "timestamp": "2024-06-15 14:22:33.123", "path": "/api/users/999", "error": "Not Found", "status": 404 }
本文转载于:https://www.php.cn/faq/2823476.html 如有侵犯,请联系zhengruancom@outlook.com删除。
免责声明:正软商城发布此文仅为传递信息,不代表正软商城认同其观点或证实其描述。