【第一篇】springboot异常事务日志处理

项目简介:


Java framework for enterprise web applications
  • Vue
  • SpringBoot 2.1.6
  • Tk.Mybatis 2.1.5
  • Swagger 2.9.2
  • SpringSession 2.1.7
  • PageHelper 2.1.5

[第一篇 异常的统一的处理]


对异常进行了统一处理,使用@Aspect和@RestControllerAdvice统一处理

@RestControllerAdvice
@Slf4j
public class TalExceptionHandler {

    /**
     * json参数异常处理
     * @param cve
     * @param httpServletRequest
     * @return
     */
    @ExceptionHandler(ConstraintViolationException.class)
    public Response methodArgNotValidException(ConstraintViolationException cve,
                                               HttpServletRequest httpServletRequest) {
        log.error(cve.getMessage(), cve);
        Set<ConstraintViolation<?>> cves = cve.getConstraintViolations();
        StringBuffer errorMsg = new StringBuffer();
        cves.forEach(ex -> errorMsg.append(ex.getMessage()));
        Response response = new Response(ObjectUtils.toString(HttpStatus.BAD_REQUEST.value()), errorMsg.toString());
        return response;
    }

    /**
     * param参数异常处理
     * @param ex
     * @param request
     * @return
     */
    @ExceptionHandler({MethodArgumentNotValidException.class})
    public Response methodDtoNotValidException(Exception ex, HttpServletRequest request) {
        log.error(ex.getMessage(), ex);
        MethodArgumentNotValidException c = (MethodArgumentNotValidException) ex;
        List<ObjectError> errors = c.getBindingResult().getAllErrors();
        StringBuffer errorMsg = new StringBuffer();
        errors.stream().forEach(x -> {
            errorMsg.append(x.getDefaultMessage()).append(";");
        });
        Response response = new Response(ObjectUtils.toString(HttpStatus.BAD_REQUEST.value()), errorMsg.toString());
        return response;
    }

    /**
     * 400 - Bad Request
     */
    @ExceptionHandler({MissingServletRequestParameterException.class})
    public Response handleMissingServletRequestParameterException(MissingServletRequestParameterException e) {
        log.error("缺少请求参数", e);
        Response response = new Response(ObjectUtils.toString(HttpStatus.BAD_REQUEST.value()),
                "缺少请求参数" + e.getParameterName());
        return response;
    }

    /**
     * 参数解析错误处理
     *
     * @param e
     * @param req
     * @return
     */
    @ExceptionHandler({HttpMessageNotReadableException.class, MethodArgumentTypeMismatchException.class})
    public Response httpMessageNotReadableException(Exception e, WebRequest req) {
        log.error(e.getMessage(), e);
        Response response = new Response(ObjectUtils.toString(HttpStatus.BAD_REQUEST.value()), "参数解析失败");
        return response;
    }
    
      /**
     * Service自定义的异常
     *
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler(ParamException.class)
    public Response paramException(ParamException e) {
        return new Response(e.getCode(), e.getMessage());
    }

    /**
     * 获取其它异常。包括500
     *
     * @param e
     * @return
     * @throws Exception
     */
    @ExceptionHandler({Exception.class})
    public Response defaultErrorHandler(Exception e) {
        log.error("其它异常Exception", e);
        Response response = new Response(TkResponseCode.ERROR_NORMAL, "处理错误");
        return response;
    }
}
/**
 * 
 * 接口返回抽象类
 * 
 * @author
 */
public class Response<T> implements Serializable
{
    private static final long serialVersionUID = 6766428592214605847L;
    
    /**
     * 返回实体类
     */
    @ApiModelProperty(value = "返回实体对象")
    private T responseEntity;
    
    /**
     * 分页实体对角
     */
    @ApiModelProperty(value = "返回分页结果集")
    private PageInfo<T> pageInfo;
    
    /**
     * 接口返回結果码
     */
    @ApiModelProperty(value = "返回状态信息")
    private MessageResult serverResult;
    
    public Response()
    {
        this.serverResult = getServerResult();
    }
    
    public Response(T t)
    {
        this.responseEntity = t;
        this.serverResult = getServerResult();
    }
    
    public Response(List<T> list)
    {
        if (list instanceof Page)
        {
            this.pageInfo = new PageInfo<T>(list,((Page<T>) list).getPages());
        }
        else
        {
            this.pageInfo = new PageInfo<T>();
            this.pageInfo.setList(list);
            this.pageInfo.setTotal(null == list ? 0 : list.size());
        }
        this.serverResult = getServerResult();
    }
    
    public Response(String resultCode,String resultMessage,String internalMessage)
    {
        this.serverResult = new MessageResult();
        serverResult.setResultCode(resultCode);
        serverResult.setResultMsg(resultMessage);
        serverResult.setInternalMsg(internalMessage);
    }
    
    public Response(String resultCode,String resultMessage)
    {
        this(resultCode,resultMessage,resultMessage);
    }

    public Response(String resultCode)
    {
        this(resultCode, TkResponseGetEContent.getEContent(resultCode), TkResponseGetEContent.getEContent(resultCode));
    }
    
    public MessageResult getServerResult()
    {
        /**
         * 默认为成功
         */
        if (serverResult == null)
        {
            serverResult = new MessageResult();
            serverResult.setResultCode(IStateCode.HTTP_200);
            serverResult.setResultMsg("操作成功");
        }
        return serverResult;
    }
    
    public void setServerResult(MessageResult serverResult)
    {
        this.serverResult = serverResult;
    }
    
    public T getResponseEntity()
    {
        return responseEntity;
    }
    
    public void setResponseEntity(T responseEntity)
    {
        this.responseEntity = responseEntity;
    }
    
    public PageInfo<T> getPageInfo()
    {
        return pageInfo;
    }
    
    public void setPageInfo(PageInfo<T> pageInfo)
    {
        this.pageInfo = pageInfo;
    }
}

你可能感兴趣的:(java)