1. 自定义异常
参考:Java自定义异常 - 简书 (jianshu.com)
2. 统一异常处理类
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import com.test.constant.CodeMsg;
import com.test.entity.Result;
import lombok.extern.slf4j.Slf4j;
/**
* 全局异常处理
* @author zrb
*/
/**
* @RestControllerAdvice注解和controller相对应,
* 若用controller,则此处用ControllerAdvice,
* 若用RestController,此处用@RestControllerAdvice
*/
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
/**
* 处理空指针的异常
* @param req
* @param e
*/
@ExceptionHandler(value = NullPointerException.class)
public Result<String> exceptionHandler(HttpServletRequest req, NullPointerException e) {
log.error("空指针异常!原因是:", e);
return new Result<String>().error(CodeMsg.ERROR, e.getMessage());
}
/**
* 参数校验异常
* @param req
* @param e
*/
@ExceptionHandler(value = MyArgumentException.class)
public Result<String> exceptionHandler(HttpServletRequest req, MyArgumentException e) {
log.error("参数校验异常:", e);
return new Result<String>().error(CodeMsg.PARA_ERROR, e.getMessage(), e.getParamData());
}
/**
* 处理其他异常
* @param req
* @param e
*/
@ExceptionHandler(value = Exception.class)
public Result<String> exceptionHandler(HttpServletRequest req, Exception e) {
log.error("系统异常!原因是:", e);
return new Result<String>().error(CodeMsg.ERROR, e.getMessage());
}
}
网友评论