SpringBoot配置全局的异常捕获 - ajax形式
warning:
这篇文章距离上次修改已过193天,其中的内容可能已经有所变动。
在Spring Boot中,可以通过@ControllerAdvice和@ExceptionHandler注解实现全局异常捕获。以下是一个示例代码,展示了如何捕获异常并返回JSON格式的响应:
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.request.WebRequest;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(Exception.class)
@ResponseBody
public ResponseEntity<Map<String, Object>> handleException(Exception e, WebRequest request) {
Map<String, Object> body = new LinkedHashMap<>();
body.put("timestamp", new Date());
body.put("message", e.getMessage());
body.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
// 可以添加更多的错误详情
return new ResponseEntity<>(body, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
这段代码定义了一个全局异常处理器,它会捕获所有类型的异常,并返回一个包含时间戳、消息和状态码的JSON对象。返回的HTTP状态码默认为500,表示服务器内部错误。在实际应用中,你可以根据需要对异常处理逻辑进行自定义,例如区分不同的异常类型,并返回不同的错误码和消息。
评论已关闭