cm-cloud/cloud-common/src/main/java/com/cm/common/advice/ResponseAdvice.java

65 lines
2.5 KiB
Java
Raw Normal View History

2019-07-27 23:03:27 +08:00
package com.cm.common.advice;
import com.alibaba.fastjson.JSON;
import com.cm.common.enums.ErrorResultCodeEnum;
import com.cm.common.exception.*;
import com.cm.common.exception.base.SystemException;
import com.cm.common.result.ErrorResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
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.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLSyntaxErrorException;
/**
* @ClassName: ResponseAdvice
* @Description: Response结果处理
* @Author: WangGeng
* @Date: 2019/2/26 5:14 PM
* @Version: 1.0
**/
@ControllerAdvice
public class ResponseAdvice {
private static final Logger LOG = LoggerFactory.getLogger(ResponseAdvice.class);
@ResponseBody
@ExceptionHandler({SystemException.class, SQLSyntaxErrorException.class})
public void responseException(HttpServletResponse response, Exception e) throws IOException {
LOG.error(e.getMessage(), e);
response.setStatus(HttpStatus.BAD_REQUEST.value());
response.setHeader("Content-Type", "application/json;charset=UTF-8");
ErrorResult result = new ErrorResult(ErrorResultCodeEnum.SYSTEM_ERROR.getValue(), "系统错误");
if (e instanceof SaveException) {
result.setCode(ErrorResultCodeEnum.SAVE_ERROR.getValue());
} else if (e instanceof RemoveException) {
result.setCode(ErrorResultCodeEnum.REMOVE_ERROR.getValue());
} else if (e instanceof UpdateException) {
result.setCode(ErrorResultCodeEnum.UPDATE_ERROR.getValue());
} else if (e instanceof SearchException) {
result.setCode(ErrorResultCodeEnum.QUERY_ERROR.getValue());
} else if (e instanceof ParamsException) {
result.setCode(ErrorResultCodeEnum.PARAMS_ERROR.getValue());
} else if (e instanceof FileException) {
result.setCode(ErrorResultCodeEnum.FILE_ERROR.getValue());
2019-08-27 11:20:57 +08:00
} else if (e instanceof AppDeviceException) {
result.setCode(ErrorResultCodeEnum.DEVICE_ERROR.getValue());
} else if (e instanceof AccessTokenException) {
2019-08-17 08:56:38 +08:00
response.setStatus(HttpStatus.UNAUTHORIZED.value());
2019-07-27 23:03:27 +08:00
}
// 自定义提示信息
if (e instanceof SystemException) {
result.setMsg(e.getMessage());
}
response.getWriter().write(JSON.toJSONString(result));
}
}