All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.gccloud.starter.common.exception.GlobalExceptionHandler Maven / Gradle / Ivy

Go to download

几乎所有的模块都依赖该模块,该模块中引入了一些常用工具类、通用的bean、全局异常处理、常量定义等

There is a newer version: 2.3.0.RELEASE
Show newest version
package com.gccloud.starter.common.exception;

import com.gccloud.starter.common.constant.GlobalConst;
import com.gccloud.starter.common.vo.R;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthorizedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;
import java.text.MessageFormat;

/**
 * 异常处理
 *
 * @Author maoshufeng
 * @Date 2020-06-19
 * @Version 1.0.0
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(AuthorizationException.class)
    public R authorizationException(AuthorizationException e) {
        log.error(ExceptionUtils.getStackTrace(e));
        R r = new R();
        r.setCode(GlobalConst.Response.Code.SERVER_ERROR);
        r.setMsg(e.getMessage());
        return r;
    }

    @ExceptionHandler(UnauthorizedException.class)
    public R unauthorizedException(AuthorizationException e) {
        log.error(MessageFormat.format("请检查该用户是否具有指定的权限:{0}", e.getMessage()));
        R r = new R();
        r.setCode(GlobalConst.Response.Code.SERVER_ERROR);
        r.setMsg("您无权限访问该接口");
        return r;
    }

    @ExceptionHandler(ExpiredJwtException.class)
    public R expiredJwtException(AuthorizationException e) {
        log.error(ExceptionUtils.getStackTrace(e));
        R r = new R();
        r.setCode(GlobalConst.Response.Code.NO_LOGIN);
        r.setMsg("用户身份已过期,请重新登录");
        return r;
    }


    @ExceptionHandler(HttpRequestMethodNotSupportedException.class)
    public R httpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.error(ExceptionUtils.getStackTrace(e));
        R r = new R();
        r.setCode(GlobalConst.Response.Code.SERVER_ERROR);
        r.setMsg("不支持该请求方式");
        return r;
    }

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(GlobalException.class)
    public R exception(HttpServletRequest request, GlobalException e) {
        log.error(ExceptionUtils.getStackTrace(e));
        R r = new R();
        r.setCode(e.getCode());
        r.setMsg(e.getMessage());
        return r;
    }

    @ExceptionHandler(Exception.class)
    public R handleException(Exception e) {
        log.error(ExceptionUtils.getStackTrace(e));
        return R.error("服务器异常");
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy