在java中,使用异常处理器返回统一响应通常依赖于spring框架提供的`@restcontrolleradvice`和`@exceptionhandler`注解。通过定义一个全局异常处理类,捕获特定或通用的异常,并在处理方法中构建统一的json响应对象(如包含状态码、消息和数据),即可实现所有接口错误时的标准化输出。

如何定义全局异常处理类并捕获特定业务异常
要捕获特定的业务异常,首先需要创建一个被`@RestControllerAdvice`注解的类,然后在其中定义一个被`@ExceptionHandler`注解的方法,指定要捕获的异常类型。该方法接收异常对象作为参数,并返回一个符合统一响应格式的对象。例如,可以定义一个`BusinessException`,并在处理器中将其转换为包含错误信息的JSON结构。

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public ResponseEntity<unifiedresponse> handleBusinessException(BusinessException ex) {
UnifiedResponse response = new UnifiedResponse();
response.setCode(ex.getCode());
response.setMessage(ex.getMessage());
response.setData(null);
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(response);
}
}
// 假设的统一响应类和业务异常类
class UnifiedResponse {
private int code;
private String message;
private Object data;
// getters and setters
}
class BusinessException extends RuntimeException {
private int code;
public BusinessException(int code, String message) {
super(message);
this.code = code;
}
// getter for code
}</unifiedresponse>
如何处理未捕获的通用异常以确保系统稳定性
除了处理已知的业务异常外,还需要处理那些未被显式捕获的运行时异常或未知异常,以防止系统暴露内部堆栈信息或返回不友好的默认错误页面。可以通过在同一个`@RestControllerAdvice`类中添加一个捕获`Exception`或`RuntimeException`的方法来实现。这种方法作为兜底策略,确保任何意外错误都能以统一的格式返回,通常记录日志并返回一个通用的错误码。
使用 Husky 将 pre-commit、pre-push 和 commit-msg 检查集成到仓库中,以便代理和开发人员在更改离开工作站之前运行相同的本地防护措施。

import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.http.ResponseEntity;
import org.springframework.http.HttpStatus;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
@ExceptionHandler(Exception.class)
public ResponseEntity<unifiedresponse> handleGenericException(Exception ex) {
log.error("Unexpected error occurred", ex);
UnifiedResponse response = new UnifiedResponse();
response.setCode(500);
response.setMessage("Internal Server Error");
response.setData(null);
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(response);
}
}</unifiedresponse>
当抛出空指针异常时统一响应会返回什么内容
当程序中发生`NullPointerException`且未被具体业务逻辑捕获时,它会被上述定义的通用异常处理器`handleGenericException`所捕获。此时,统一响应将返回状态码为500,消息为"Internal Server Error",数据字段为null的JSON对象。同时,服务器端日志会记录完整的异常堆栈信息,以便开发人员排查问题。这种处理方式避免了向客户端暴露具体的代码错误细节,保证了接口的健壮性和安全性。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










