异常信息处理类
@Slf4j
@RestControllerAdvice
public class BaseExceptionHandler extends Exception{
private final Logger logger = LoggerFactory.getLogger(BaseExceptionHandler.class);
@ExceptionHandler(value = {NullPointerException.class})
@ResponseStatus(HttpStatus.BAD_REQUEST)
public R nullPointerExceptionHandler(HttpServletResponse response, Exception e) {
logger.error("检测到空指针异常:{}", e.getMessage());
e.printStackTrace();
return R.err(e.getMessage());
}
@ResponseBody
@ExceptionHandler(value = Exception.class)
public R exceptionHandler(Exception e) {
logger.error("检测到异常信息:{}", e.getMessage());
e.printStackTrace();
return R.err(e.getMessage());
}
}
封装自定义异常类
public class BusinessException extends RuntimeException {
private static final long serialVersionUID = 5046932872928928307L;
private static final Logger LOGGER = LoggerFactory.getLogger(BusinessException.class);
public BusinessException() {
}
public BusinessException(String message) {
super(message);
LOGGER.error("自定义异常信息:{}", message);
}
public BusinessException(String message, Throwable cause) {
super(message, cause);
String exMsg = cause.getMessage();
LOGGER.error("自定义异常信息:{},系统异常信息:{}", message, exMsg);
}
public BusinessException(Throwable cause) {
super(cause);
String exMsg = cause.getMessage();
LOGGER.error("系统异常信息:{}", exMsg);
}
public BusinessException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
String exMsg = cause.getMessage();
LOGGER.error("自定义异常信息:{},系统异常信息:{}", message, exMsg);
}
}
自定义异常类的使用
@RestController
@RequestMapping("wares")
public class WaresController {
private static final Logger LOGGER = LoggerFactory.getLogger(WaresController.class);
@PostMapping("getAllWares")
public R getAllWares(HttpServletRequest req, HttpServletResponse res){
if (ObjectUtils.isBlank(null)) {
throw new BusinessException("检测到NULL异常信息!");
}
LOGGER.info("你猜我会不会被执行。。。。");
return R.ok("调用成功了!");
}
}
自定义返回实体对象
public class R extends HashMap<String, Object> implements Serializable {
private static final long serialVersionUID = 1L;
public R() {
}
public static R ok(Object data) {
R r = new R();
r.put("flag", true);
r.put("msg", "成功!");
r.put("code", 200);
r.put("data", data);
return r;
}
public static R ok(Object data, String msg) {
R r = new R();
r.put("flag", true);
r.put("msg", msg);
r.put("code", 200);
r.put("data", data);
return r;
}
public static R err() {
R r = new R();
r.put("flag", false);
r.put("msg", "服务器返回失败!");
r.put("code", 500);
r.put("data", null);
return r;
}
public static R err(String msg) {
R r = new R();
r.put("flag", false);
r.put("msg", msg);
r.put("code", 500);
return r;
}
}
测试结果