ErrorHandler.java 1.86 KB
package com.myxrk.rbac.aspect;

import com.myxrk.rbac.exception.BaseException;
import com.myxrk.rbac.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@Slf4j
@RestControllerAdvice
public class ErrorHandler {

    @ExceptionHandler(Throwable.class)
    public Result<Object> handleException(Exception e) {
        log.error("Unknown Exception was thrown!", e);
        return Result.error(500, e.getMessage());
    }

    @ExceptionHandler(NoResourceFoundException.class)
    public ModelAndView handleNoResourceFoundException(Exception e) {
        log.error("Unknown Exception was thrown!", e);
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("404");
        return modelAndView;
    }


    @ExceptionHandler(BaseException.class)
    public Result<Object> handleCustomException(BaseException e) {
        log.warn("Biz Exception was thrown!", e);
        return Result.error(e.getCode(), e.getMessage());
    }

    @ExceptionHandler(AuthenticationException.class)
    @ResponseBody
    public Result<String> handleException(AuthenticationException e) {
        log.warn("AuthenticationException was thrown!", e);
        return Result.error(601, "授权失败");
    }

    @ExceptionHandler(AuthorizationException.class)
    @ResponseBody
    public Result<String> handleException(AuthorizationException e) {
        log.warn("AuthorizationException was thrown!", e);
        return Result.error(631, "授权失败");
    }


}