Spring Boot全局异常处理
import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * 全局异常处理 */ @ControllerAdvice public class MyExceptionHandler { /** * 异常处理 * @param request * @param e * @param response * @return */ @ExceptionHandler(value = {Exception.class}) //要拦截的异常 @ResponseBody public String MyException(HttpServletRequest request,Exception e, HttpServletResponse response) { //错误信息 e.getMessage(); //可以在这里设置返回的错误格式 return null; } }
自定义异常实体类
import lombok.Getter; import org.springframework.http.HttpStatus; import static org.springframework.http.HttpStatus.BAD_REQUEST; /** * @ClassName 自定义异常 **/ @Getter public class MyException extends RuntimeException{ private Integer status = BAD_REQUEST.value(); public MyException(String msg){ super(msg); } public MyException(HttpStatus status,String msg){ super(msg); this.status = status.value(); } }
-----------------------有任何问题可以在评论区评论,也可以私信我,我看到的话会进行回复,欢迎大家指教------------------------
(蓝奏云官网有些地址失效了,需要把请求地址lanzous改成lanzoux才可以)