更新异常处理方式

This commit is contained in:
wangkang
2017-07-29 10:18:37 +08:00
parent 8c4e90fe98
commit fa8f3d78f4
5 changed files with 102 additions and 326 deletions
@@ -8,8 +8,8 @@ package org.itkk.udf.core;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import org.itkk.udf.core.exception.ErrorCode;
import org.itkk.udf.core.exception.ErrorResult;
import org.springframework.http.HttpStatus;
import java.io.Serializable;
import java.util.UUID;
@@ -37,13 +37,13 @@ public class RestResponse<T> implements Serializable {
* 描述 : 状态码(业务定义)
*/
@ApiModelProperty(value = "状态码(业务定义)", required = true, dataType = "string")
private String code = "SUCCESS";
private String code = Integer.toString(HttpStatus.OK.value());
/**
* 描述 : 状态码描述(业务定义)
*/
@ApiModelProperty(value = "状态码描述(业务定义)", required = true, dataType = "string")
private String message = "操作成功";
private String message = HttpStatus.OK.getReasonPhrase();
/**
* 描述 : 结果集(泛型)
@@ -77,13 +77,13 @@ public class RestResponse<T> implements Serializable {
/**
* 描述 : 构造函数
*
* @param errorCode 错误码
* @param error 错误
* @param httpStatus http状态
* @param error 错误
*/
public RestResponse(ErrorCode errorCode, ErrorResult error) {
public RestResponse(HttpStatus httpStatus, ErrorResult error) {
super();
this.code = errorCode.name();
this.message = errorCode.value();
this.code = Integer.toString(httpStatus.value());
this.message = httpStatus.getReasonPhrase();
this.error = error;
}
@@ -1,76 +0,0 @@
/**
* ErrorCode.java
* Created at 2016-09-27
* Created by wangkang
* Copyright (C) 2016 itkk.org, All rights reserved.
*/
package org.itkk.udf.core.exception;
/**
* 描述 : 错误代码枚举
*
* @author wangkang
*/
public enum ErrorCode {
/**
* 描述 : 系统内部错误
*/
ERROR("system internal error"),
/**
* 描述 : http服务错误
*/
HTTP_ERROR("http error"),
/**
* 描述 : 参数校验错误
*/
PARAMETER_VALID_ERROR("parameter check error"),
/**
* 描述 : 方法不允许
*/
METHOD_NOT_ALLOWED("method not allowed"),
/**
* 描述 : Http媒体类型不可接受
*/
HTTP_MEDIA_TYPE_NOT_ACCEPTABLE("Http Media Type Not Acceptable"),
/**
* 描述 : 资源不存在
*/
NO_RESOURCE_FOUND("resource does not exist"),
/**
* 描述 : 认证错误
*/
AUTH_ERROR("auth error"),
/**
* 描述 : 权限错误
*/
PERMISSION_ERROR("Permission error");
/**
* <p>
* Field value: 参数值
* </p>
*/
private String value = null;
/**
* <p>
* Description: 构造函数
* </p>
*
* @param value 构造函数
*/
ErrorCode(String value) {
this.value = value;
}
/**
* <p>
* Description: 放回int值
* </p>
*
* @return value 放回int值
*/
public String value() {
return this.value;
}
}
@@ -0,0 +1,93 @@
package org.itkk.udf.core.exception.handle;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.itkk.udf.core.ApplicationConfig;
import org.itkk.udf.core.RestResponse;
import org.itkk.udf.core.exception.ErrorResult;
import org.itkk.udf.core.exception.SystemRuntimeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.client.RestClientResponseException;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import java.io.IOException;
import java.util.Date;
/**
* ExceptionHandle
*/
@ControllerAdvice
public class ExceptionHandle extends ResponseEntityExceptionHandler {
/**
* 描述 : 系统配置
*/
@Autowired
private ApplicationConfig applicationConfig;
/**
* 描述 : objectMapper
*/
@Autowired
private ObjectMapper objectMapper;
/**
* 异常处理
*
* @param ex ex
* @param request request
* @return ResponseEntity<Object>
*/
@ExceptionHandler(value = Exception.class)
public ResponseEntity<Object> exception(Exception ex, WebRequest request) {
ResponseEntity<Object> objectResponseEntity = this.handleException(ex, request);
return this.handleExceptionInternal(ex, null, objectResponseEntity.getHeaders(), objectResponseEntity.getStatusCode(), request);
}
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
RestResponse<String> result = new RestResponse<>(status, buildError(ex));
//判断是不是rest请求异常
if (ex instanceof RestClientResponseException) {
try {
//获得子错误
RestClientResponseException restClientResponseException = (RestClientResponseException) ex;
String data = restClientResponseException.getResponseBodyAsString();
if (StringUtils.isNotBlank(data)) {
//解析子错误
RestResponse<String> child = objectMapper.readValue(data, objectMapper.getTypeFactory().constructParametricType(RestResponse.class, String.class));
//设置子错误
result.getError().setChild(child);
}
} catch (IOException e) {
throw new SystemRuntimeException(e);
}
}
return super.handleExceptionInternal(ex, result, headers, status, request);
}
/**
* 描述 : 构造错误响应对象
*
* @param exception 异常
* @return 错误响应对象
*/
private ErrorResult buildError(Exception exception) {
ErrorResult error = new ErrorResult();
error.setType(exception.getClass().getName());
error.setMessage(ExceptionUtils.getMessage(exception));
if (applicationConfig.isOutputExceptionStackTrace()) {
error.setStackTrace(ExceptionUtils.getStackTrace(exception));
}
error.setDate(new Date());
logger.error(exception.getClass().getName(), exception);
return error;
}
}
@@ -1,240 +0,0 @@
/**
* ExceptionMapping.java
* Created at 2016-09-20
* Created by wangkang
* Copyright (C) 2016 itkk.org, All rights reserved.
*/
package org.itkk.udf.core.exception.handle;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.itkk.udf.core.ApplicationConfig;
import org.itkk.udf.core.RestResponse;
import org.itkk.udf.core.exception.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.HttpMediaTypeNotAcceptableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ControllerAdvice;
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.client.RestClientResponseException;
import org.springframework.web.servlet.NoHandlerFoundException;
import java.io.IOException;
import java.util.Date;
/**
* 描述 : 全局异常处理
*
* @author wangkang
*/
@ControllerAdvice
public class ExceptionMapping {
/**
* 描述 : 日志
*/
private static final Logger LOGGER = LoggerFactory.getLogger(ExceptionMapping.class);
/**
* 描述 : 系统配置
*/
@Autowired
private ApplicationConfig applicationConfig;
/**
* 描述 : objectMapper
*/
@Autowired
private ObjectMapper objectMapper;
/**
* 描述 : 构造函数
*/
public ExceptionMapping() {
LOGGER.info("ExceptionMapping initialize");
}
/**
* 描述 : 捕获PermissionException异常(权限异常)
*
* @param exception 异常
* @return 错误信息
*/
@ExceptionHandler(value = PermissionException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
@ResponseBody
public RestResponse<String> permissionException(PermissionException exception) {
return new RestResponse<>(ErrorCode.PERMISSION_ERROR, buildError(exception));
}
/**
* 描述 : 捕获AuthException异常(认证异常)
*
* @param exception 异常
* @return 错误信息
*/
@ExceptionHandler(value = AuthException.class)
@ResponseStatus(HttpStatus.UNAUTHORIZED)
@ResponseBody
public RestResponse<String> authException(AuthException exception) {
return new RestResponse<>(ErrorCode.AUTH_ERROR, buildError(exception));
}
/**
* 描述 : 捕获ParameterValidException异常(参数校验错误)
*
* @param exception 异常
* @return 错误信息
*/
@ExceptionHandler(value = ParameterValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
public RestResponse<String> parameterValidException(ParameterValidException exception) {
return new RestResponse<>(ErrorCode.PARAMETER_VALID_ERROR, buildError(exception));
}
/**
* 描述 : 捕获RestClientResponseException异常(http服务异常)
*
* @param exception 异常
* @return 错误信息
* @throws IOException 异常
*/
@ExceptionHandler(value = RestClientResponseException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public RestResponse<String> restClientResponseException(RestClientResponseException exception)
throws IOException {
//获得错误
ErrorResult errorResult = buildError(exception);
//获得子错误
String result = exception.getResponseBodyAsString();
if (StringUtils.isNotBlank(result)) {
//解析子错误
RestResponse<String> child = objectMapper.readValue(exception.getResponseBodyAsString(),
objectMapper.getTypeFactory().constructParametricType(RestResponse.class, String.class));
//设置子错误
errorResult.setChild(child);
}
//返回
return new RestResponse<>(ErrorCode.HTTP_ERROR, errorResult);
}
/**
* 描述 : 捕获NoHandlerFoundException异常(资源不存在)
*
* @param exception 异常
* @return 错误信息
*/
@ExceptionHandler(value = NoHandlerFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
@ResponseBody
public RestResponse<String> noHandlerFoundException(NoHandlerFoundException exception) {
return new RestResponse<>(ErrorCode.NO_RESOURCE_FOUND, buildError(exception));
}
/**
* 描述 : 捕获httpRequestMethodNotSupportedException异常(方法不允许)
*
* @param exception 异常
* @return 错误信息
*/
@ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
@ResponseStatus(HttpStatus.METHOD_NOT_ALLOWED)
@ResponseBody
public RestResponse<String> httpRequestMethodNotSupportedException(
HttpRequestMethodNotSupportedException exception) {
return new RestResponse<>(ErrorCode.METHOD_NOT_ALLOWED, buildError(exception));
}
/**
* 描述 : 捕获HttpMediaTypeNotAcceptableException异常(Http媒体类型不可接受)
*
* @param exception 异常
* @return 错误信息
*/
@ExceptionHandler(value = HttpMediaTypeNotAcceptableException.class)
@ResponseStatus(HttpStatus.NOT_ACCEPTABLE)
@ResponseBody
public RestResponse<String> httpMediaTypeNotAcceptableException(
HttpMediaTypeNotAcceptableException exception) {
return new RestResponse<>(ErrorCode.HTTP_MEDIA_TYPE_NOT_ACCEPTABLE, buildError(exception));
}
/**
* 描述 : 捕获SystemException异常(系统检查型异常)
*
* @param exception 异常
* @return 错误信息
*/
@ExceptionHandler(value = SystemException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public RestResponse<String> systemException(SystemException exception) {
return new RestResponse<>(ErrorCode.ERROR, buildError(exception));
}
/**
* 描述 : 捕获SystemRuntimeException异常(系统运行时型异常)
*
* @param exception 异常
* @return 错误信息
*/
@ExceptionHandler(value = SystemRuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public RestResponse<String> systemRuntimeException(SystemRuntimeException exception) {
return new RestResponse<>(ErrorCode.ERROR, buildError(exception));
}
/**
* 描述 : 捕获Exception异常(检查型异常)
*
* @param exception 异常
* @return 错误信息
*/
@ExceptionHandler(value = Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public RestResponse<String> exception(Exception exception) {
return new RestResponse<>(ErrorCode.ERROR, buildError(exception));
}
/**
* 描述 : 捕获RuntimeException异常(运行时异常)
*
* @param exception 异常
* @return 错误信息
*/
@ExceptionHandler(value = RuntimeException.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public RestResponse<String> runtimeException(RuntimeException exception) {
return new RestResponse<>(ErrorCode.ERROR, buildError(exception));
}
/**
* 描述 : 构造错误响应对象
*
* @param exception 异常
* @return 错误响应对象
*/
private ErrorResult buildError(Exception exception) {
ErrorResult error = new ErrorResult();
error.setType(exception.getClass().getName());
error.setMessage(ExceptionUtils.getMessage(exception));
if (applicationConfig.isOutputExceptionStackTrace()) {
error.setStackTrace(ExceptionUtils.getStackTrace(exception));
}
error.setDate(new Date());
LOGGER.error(exception.getClass().getName(), exception);
return error;
}
}
@@ -8,7 +8,6 @@ package org.itkk.udf.mail.web;
import org.itkk.udf.core.RestResponse;
import org.itkk.udf.core.domain.mail.MailInfo;
import org.itkk.udf.core.exception.ErrorCode;
import org.itkk.udf.core.exception.ParameterValidException;
import org.itkk.udf.mail.service.MailService;
import org.springframework.beans.factory.annotation.Autowired;
@@ -38,7 +37,7 @@ public class MailController implements IMailController {
throws MessagingException {
//校验
if (result.hasErrors()) {
throw new ParameterValidException(ErrorCode.PARAMETER_VALID_ERROR.value(),
throw new ParameterValidException("校验失败",
result.getAllErrors());
}
//发送