需求:
自己控制系统中的一些业务、数据等异常的捕获和处理。
实现:
1、定义全局异常类
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
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.bind.annotation.RestControllerAdvice;
/**
*
* @ClassName: GlobalExceptionHandler
* @Description: 全局的的异常拦截器
*
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* 全局异常.
*
* @param e the e
* @return R
*/
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public R exception(Exception e) {
log.info("保存全局异常信息 ex={}", e.getMessage(), e);
return new R<>(e);
}
/**
* XXX服务业务异常.
*
* @param e the e
* @return R
*/
@ExceptionHandler(PartnerServiceException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public R exception(PartnerServiceException e) {
log.info("保存XXX服务异常信息 ex={}", e.getMessage(), e);
return new R<>(e);
}
}
2、定义自定义异常类
/**
* @Author chenqi
* @Description XXX服务业务异常
**/
public class PartnerServiceException extends RuntimeException {
private static final long serialVersionUID = 1L;
public PartnerServiceException() {
}
public PartnerServiceException(String message) {
super(message);
}
public PartnerServiceException(Throwable cause) {
super(cause);
}
public PartnerServiceException(String message, Throwable cause) {
super(message, cause);
}
public PartnerServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
使用方式
在需要抛出异常的代码处直接throw即可
throw new PartnerServiceException(PartnerErrorEnum.PARTNER_SERVICE_ERROR_10001.getMsg());
异常信息可以配合枚举类使用,将异常文案集中存放,便于维护和重复利用。
/**
* @Author chenqi
* @Description XXX服务 业务异常枚举
**/
public enum PartnerErrorEnum{
/************** 业务异常 *****************/
/** xxx不存在 */
PARTNER_SERVICE_ERROR_10001(10001, "xxx不存在") {},
;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
private PartnerErrorEnum(int code, String msg) {
this.code = code;
this.msg = msg;
}
private int code;
private String msg;
}
这样,自定义异常的配置和使用就完成了。
如果该文章有帮助到您,就留言点个赞吧!您的支持与肯定是我持续更新最大的动力。