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(); } }