在做项目的时候需要对自定义异常做捕获和处理,现在将代码记录下来便于以后查阅。
1、全局异常捕捉处理
@ControllerAdvice(
annotations = {RestController.class}
)
public class ExceptionHandlerAdvice {
private static final Logger LOGGER = LoggerFactory.getLogger(this.getCLass());
@ExceptionHandler(EntityTransException.class)
public ResponseResult entityTransExceptionHandle(HttpServletRequest request,EntityTransException e){
LOGGER.error("********************Throw EntityTransException.url:{} ERROR:{}********************",request.getRequestURL(), e.getMessage(), e);
ResponseResult result = new ResponseResult();
result.setSuccess(false);
result.setMessage(ResultCode.ERROR_ENTITY_TRANS.getMessage() + "。异常原因:" + e.getMessage());
result.setCode(ResultCode.ERROR_ENTITY_TRANS.getCode());
return result;
}
@ExceptionHandler(SqlException.class)
public ResponseResult sqlExceptionHandle(HttpServletRequest request,SqlException e){
LOGGER.error("********************Throw SqlException.url:{} ERROR:{}********************",request.getRequestURL(), e.getMessage(), e);
ResponseResult result = new ResponseResult();
result.setSuccess(false);
result.setMessage(ResultCode.ERROR_SQL_CHECK.getMessage() + "。异常原因:" + e.getMessage());
result.setCode(ResultCode.ERROR_SQL_CHECK.getCode());
return result;
}
@ExceptionHandler(Exception.class)
public ResponseResult exceptionHandle(HttpServletRequest request,Exception e){
LOGGER.error("********************Throw Exception.url:{} ERROR:{}********************",request.getRequestURL(), e.getMessage(), e);
ResponseResult result = new ResponseResult();
result.setSuccess(false);
result.setMessage(ResultCode.ERROR.getMessage());
result.setCode(ResultCode.ERROR.getCode());
return result;
}
}
2、自定义异常类
package com.czgo.exception;
/**
* 自定义异常类(继承运行时异常)
* @author zhangzhixiang
* @version 2018/11/09
*/
public class SqlException extends RuntimeException {
private static final long serialVersionUID = 1L;
/**
* 错误编码
*/
private String errorCode;
/**
* 消息是否为属性文件中的Key
*/
private boolean propertiesKey = true;
/**
* 构造一个基本异常.
*
* @param cause 异常信息
*
*/
public SqlException(Throwable cause)
{
super(cause);
}
/**
* 构造一个基本异常.
*
* @param message 信息描述
*
*/
public SqlException(String message)
{
super(message);
}
/**
* 构造一个基本异常.
*
* @param errorCode 错误编码
* @param message 信息描述
*
*/
public SqlException(String errorCode, String message)
{
this(errorCode, message, true);
}
/**
* 构造一个基本异常.
*
* @param errorCode 错误编码
* @param message
*
*/
public SqlException(String errorCode, String message, Throwable cause)
{
this(errorCode, message, cause, true);
}
/**
* 构造一个基本异常.
*
* @param errorCode 错误编码
* @param message 信息描述
* @param propertiesKey 消息是否为属性文件中的Key
*
*/
public SqlException(String errorCode, String message, boolean propertiesKey)
{
super(message);
this.setErrorCode(errorCode);
this.setPropertiesKey(propertiesKey);
}
/**
* 构造一个基本异常.
*
* @param errorCode 错误编码
* @param message 信息描述
*
*/
public SqlException(String errorCode, String message, Throwable cause, boolean propertiesKey)
{
super(message, cause);
this.setErrorCode(errorCode);
this.setPropertiesKey(propertiesKey);
}
/**
* 构造一个基本异常.
*
* @param message 信息描述
* @param cause 根异常类(可以存入任何异常)
*
*/
public SqlException(String message, Throwable cause)
{
super(message, cause);
}
public String getErrorCode()
{
return errorCode;
}
public void setErrorCode(String errorCode)
{
this.errorCode = errorCode;
}
public boolean isPropertiesKey()
{
return propertiesKey;
}
public void setPropertiesKey(boolean propertiesKey)
{
this.propertiesKey = propertiesKey;
}
}
3、Controller层
@RestController
@RequestMapping("/user")
public class FileController extends ExceptionHandlerAdvice {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
@RequestMapping(value = "/selectByCondition", method = RequestMethod.POST)
public ResponseResult selectByCondition() throws Exception {
throw new EntityTransException("这是一个自定义实体转换异常,这条异常会在ExceptionHandlerAdvice的entityTransExceptionHandle方法中被拦截");
}
@RequestMapping(value = "/update", method = RequestMethod.POST)
public ResponseResult update() throws Exception {
throw new SqlException("这是一个自定义SQL异常,这条异常会在ExceptionHandlerAdvice的sqlExceptionHandle方法中被拦截");
}
}
4、封装返回实体
public class ResponseResult implements Serializable {
private static final long serialVersionUID = 6054052582421291408L;
private String message;
private Object data;
private int code;
private boolean success;
private Long total;
public ResponseResult(){}
public ResponseResult(boolean success, Object data) {
this.success = success;
this.data = data;
}
public ResponseResult(boolean success, String message, Object data) {
this.success = success;
this.message = message;
this.data = data;
}
public String getMessage() {
return message;
}
public ResponseResult setMessage(String message) {
this.message = message;
return this;
}
public Object getData() {
return data;
}
public ResponseResult setData(Object data) {
this.data = data;
return this;
}
public boolean getSuccess() {
return success;
}
public ResponseResult setSuccess(boolean success) {
this.success = success;
return this;
}
public int getCode() {
return code;
}
public ResponseResult setCode(int code) {
this.code = code;
return this;
}
public Long getTotal() {
return success;
}
public ResponseResult setTotal(Long total) {
this.total = total;
return this;
}
}
5、补充
@ControllerAdvice(
annotations = {RestController.class}
)
public class ExceptionHandlerAdvice {
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionHandlerAdvice.class);
/**
* 400错误
*
* @param e
* @return java.lang.ResponseResult
* @author zxzhang
* @date 2019/6/27
*/
@ExceptionHandler({HttpMessageNotReadableException.class, TypeMismatchException.class, MissingServletRequestParameterException.class})
public ResponseResult requestNotReadable(HttpServletRequest request, HttpMessageNotReadableException e) {
return resultFormat(request, ResponseEnum.RESPONSE_CODE_PARAM_ERR, e);
}
/**
* 404错误
*
* @param e
* @return java.lang.ResponseResult
* @author zxzhang
* @date 2019/6/27
*/
@ExceptionHandler({NoHandlerFoundException.class})
public ResponseResult requestNotReadable(HttpServletRequest request, NoHandlerFoundException e) {
return resultFormat(request, ResponseEnum.RESPONSE_CODE_NOT_FOUND, e);
}
/**
* 405错误
*
* @param e
* @return java.lang.ResponseResult
* @author zxzhang
* @date 2019/6/27
*/
@ExceptionHandler({HttpRequestMethodNotSupportedException.class})
public ResponseResult request405(HttpServletRequest request, HttpRequestMethodNotSupportedException e) {
return resultFormat(request, ResponseEnum.RESPONSE_CODE_METHOD_NOT_SUPPORT, e);
}
/**
* 406错误
*
* @param e
* @return java.lang.ResponseResult
* @author zxzhang
* @date 2019/6/27
*/
@ExceptionHandler({HttpMediaTypeNotAcceptableException.class})
public ResponseResult request406(HttpServletRequest request, HttpMediaTypeNotAcceptableException e) {
return resultFormat(request, ResponseEnum.RESPONSE_CODE_TYPE_NOT_ACCEPTABLE, e);
}
/**
* Throwable拦截器
*
* @param request
* @param e
* @return com.openailab.oascloud.common.model.ResponseResult
* @author zxzhang
* @date 2019/6/27
*/
@ExceptionHandler(Throwable.class)
public ResponseResult exceptionHandle(HttpServletRequest request, Throwable e) {
return resultFormat(request, ResponseEnum.RESPONSE_CODE_FAIL, e);
}
/**
* 格式封装
*
* @param request
* @param responseEnum
* @param e
* @return com.openailab.oascloud.common.model.ResponseResult
* @author zxzhang
* @date 2019/6/27
*/
private ResponseResult resultFormat(HttpServletRequest request, ResponseEnum responseEnum, Throwable e) {
LOGGER.error("********************Throw Exception.url:{} ERROR:{}********************", request.getRequestURL(), e.getMessage(), e);
ResponseResult result = new ResponseResult();
result.setstatus(CommonConst.RESPONSE_FAIL);
result.setMessage(responseEnum.getMsg());
result.setCode(responseEnum.getCode());
return result;
}
}
全篇文章完全纯手打,如果觉得对您有帮助,记得加关注给好评哟~~