Search in sources :

Example 1 with ResultCode

use of cn.lili.common.enums.ResultCode in project lilishop by lilishop.

the class GlobalControllerExceptionHandler method handleServiceException.

/**
 * 自定义异常
 *
 * @param e
 * @return
 */
@ExceptionHandler(ServiceException.class)
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
public ResultMessage<Object> handleServiceException(HttpServletRequest request, final Exception e, HttpServletResponse response) {
    // 如果是自定义异常,则获取异常,返回自定义错误消息
    if (e instanceof ServiceException) {
        ServiceException serviceException = ((ServiceException) e);
        ResultCode resultCode = serviceException.getResultCode();
        Integer code = null;
        String message = null;
        if (resultCode != null) {
            code = resultCode.code();
            message = resultCode.message();
        }
        // 如果有扩展消息,则输出异常中,跟随补充异常
        if (!serviceException.getMsg().equals(ServiceException.DEFAULT_MESSAGE)) {
            message += ":" + serviceException.getMsg();
        }
        log.error("全局异常[ServiceException]:{}-{}", serviceException.getResultCode().code(), serviceException.getResultCode().message(), e);
        return ResultUtil.error(code, message);
    } else {
        log.error("全局异常[ServiceException]:", e);
    }
    // 默认错误消息
    String errorMsg = "服务器异常,请稍后重试";
    if (e != null && e.getMessage() != null && e.getMessage().length() < MAX_LENGTH) {
        errorMsg = e.getMessage();
    }
    return ResultUtil.error(ResultCode.ERROR.code(), errorMsg);
}
Also used : ResultCode(cn.lili.common.enums.ResultCode) ExceptionHandler(org.springframework.web.bind.annotation.ExceptionHandler) ResponseStatus(org.springframework.web.bind.annotation.ResponseStatus)

Aggregations

ResultCode (cn.lili.common.enums.ResultCode)1 ExceptionHandler (org.springframework.web.bind.annotation.ExceptionHandler)1 ResponseStatus (org.springframework.web.bind.annotation.ResponseStatus)1