Spring Boot API如何实现抛出自定义异常并返回指定结构JSON响应
实现说明
Spring Boot原生支持该需求,通过Spring MVC自带的全局异常处理组件即可完成定制,不需要引入第三方依赖,具体实现步骤如下:
- 第一步:自定义业务异常类,用于携带自定义状态码和错误信息
public class BusinessException extends RuntimeException { private final int statusCode; private final String customMessage; public BusinessException(int statusCode, String customMessage) { super(customMessage); this.statusCode = statusCode; this.customMessage = customMessage; } public int getStatusCode() { return statusCode; } public String getCustomMessage() { return customMessage; } }
- 第二步:定义和预期结构匹配的响应类
首先定义单条错误详情的实体,对应结构里error数组下的元素:
import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class ErrorDetail { private Integer statusCode; private String customMessage; private String timestamp; public ErrorDetail(Integer statusCode, String customMessage) { this.statusCode = statusCode; this.customMessage = customMessage; // 可按需调整时间格式 this.timestamp = LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE_TIME); } // 省略getter/setter public Integer getStatusCode() { return statusCode; } public String getCustomMessage() { return customMessage; } public String getTimestamp() { return timestamp; } }
再定义外层响应实体:
import java.util.List; public class ErrorResponse { private List<ErrorDetail> error; public ErrorResponse(List<ErrorDetail> error) { this.error = error; } public List<ErrorDetail> getError() { return error; } }
- 第三步:编写全局异常处理器,拦截所有控制器抛出的异常,统一封装成你需要的结构返回
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.RestControllerAdvice; import java.util.List; @RestControllerAdvice public class GlobalExceptionHandler { // 拦截自定义业务异常 @ExceptionHandler(BusinessException.class) public ResponseEntity<List<ErrorResponse>> handleBusinessException(BusinessException e) { ErrorDetail detail = new ErrorDetail(e.getStatusCode(), e.getCustomMessage()); ErrorResponse errorResponse = new ErrorResponse(List.of(detail)); // 匹配你给出的示例,最外层包裹数组返回,同时设置对应HTTP状态码 return new ResponseEntity<>(List.of(errorResponse), HttpStatus.valueOf(e.getStatusCode())); } // 可按需扩展其他异常的处理逻辑,比如参数校验异常、系统500异常等 @ExceptionHandler(Exception.class) public ResponseEntity<List<ErrorResponse>> handleDefaultException(Exception e) { ErrorDetail detail = new ErrorDetail(500, "系统内部错误"); ErrorResponse errorResponse = new ErrorResponse(List.of(detail)); return new ResponseEntity<>(List.of(errorResponse), HttpStatus.INTERNAL_SERVER_ERROR); } }
- 使用方式:业务逻辑中直接抛出自定义异常即可,框架会自动拦截并返回你定义的结构
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class TestController { @GetMapping("/test") public String test() { // 业务校验不通过时直接抛出异常 boolean checkFail = true; if (checkFail) { throw new BusinessException(400, "请求参数非法"); } return "success"; } }
提示:你给出的示例结构最外层为数组,实际生产使用中更推荐直接返回对象结构作为响应,不需要额外包裹一层数组,只需要调整全局异常处理器的返回值类型,直接返回
ErrorResponse实例即可,调整成本极低。
内容的提问来源于stack exchange,提问作者Varox
相关产品推荐
相关产品推荐

