功能描述
当控制器方法抛出指定类型的异常时,被 @ExceptionHandler
注解标注的方法会被调用,用于处理异常情况,例如返回特定的错误响应、记录错误日志等
代码示例
针对项目最全局异常处理,返回指定格式
import fri.bhlz.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindException;
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.web.multipart.MaxUploadSizeExceededException;
import java.io.PrintWriter;
import java.io.StringWriter;
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {
@Value("${spring.servlet.multipart.max-file-size}")
private String MAX_SIZE;
/**
* 全局异常
*
* @param e
* @return
*/
@ResponseBody
@ResponseStatus(HttpStatus.OK)
@ExceptionHandler(Exception.class)
public Result handleException(Exception e) {
String msg = "系统异常";
if (e instanceof MaxUploadSizeExceededException) {
msg = "文件上传大小限制为:" + MAX_SIZE;
}
if (e instanceof BindException) {
msg = ((BindException) e).getBindingResult().getFieldError().getDefaultMessage();
}
e.printStackTrace();
log.error("系统捕获异常");
log.error(e.getMessage());
StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw, true));
log.error(sw.toString());
return new Result(-1, msg, null);
}
}