SpringBoot项目添加全局异常处理
为了在Spring Boot项目中添加异常处理,你可以使用Spring提供的@ControllerAdvice注解来定义一个全局的异常处理类。
在异常处理类中,你可以使用@ExceptionHandler注解来处理特定类型的异常。
下面是一个基础的全局异常处理类的例子:
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.bind.annotation.ResponseStatus;
import org.springframework.http.HttpStatus;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(value = Exception.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleException(Exception e) {
// 你可以在这里添加你自己的处理逻辑,例如记录日志等
return "Unexpected error: " + e.getMessage();
}
@ExceptionHandler(value = YourCustomException.class)
@ResponseBody
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleCustomException(YourCustomException e) {
// 这里处理你自定义的异常类型
return e.getMessage();
}
}
在上面的例子中,我们定义了两个异常处理器。第一个处理器会处理所有的Exception类型的异常,而第二个处理器会处理YourCustomException类型的异常。每个处理器都会返回一个自定义的错误消息给客户端。
注意这只是一个基本的例子,你可能需要根据自己的业务需求对其进行扩展或调整。
如果你希望返回更复杂的错误信息,可以创建一个自定义的错误响应类。例如:
public class ErrorResponse {
private int status;
private String message;
// getters and setters
}
然后在你的异常处理器中,返回这个类的实例,而不是一个字符串:
@ExceptionHandler(value = Exception.class)
@ResponseBody
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public ErrorResponse handleException(Exception e) {
ErrorResponse errorResponse = new ErrorResponse();
errorResponse.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
errorResponse.setMessage("Unexpected error: " + e.getMessage());
return errorResponse;
}
这样你的API就可以返回更详细的错误信息了。
浙公网安备 33010602011771号