package com.fd.controller; import com.fd.util.R; import org.apache.shiro.ShiroException; import org.apache.shiro.authc.AuthenticationException; import org.apache.shiro.authc.IncorrectCredentialsException; import org.apache.shiro.authc.UnknownAccountException; import org.apache.shiro.authz.UnauthorizedException; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestControllerAdvice; import javax.servlet.http.HttpServletRequest; /** * 统一捕捉异常,自定义返回参数 * 这里只可以捕获controller层的异常。 */ @RestControllerAdvice public class ExceptionController { // 捕捉shiro的异常 @ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler(ShiroException.class) public R handle401(ShiroException e) { return new R(40002, e.getMessage()); } // 捕捉UnauthorizedException @ResponseStatus(HttpStatus.UNAUTHORIZED) @ExceptionHandler(UnauthorizedException.class) public R handle401() { return new R(40003, "Unauthorized"); } // 捕捉其他所有异常 @ExceptionHandler(Exception.class) @ResponseStatus(HttpStatus.BAD_REQUEST) public R globalException(HttpServletRequest request, Throwable ex) { return new R(getStatus(request).value(), ex.getMessage()); } private HttpStatus getStatus(HttpServletRequest request) { Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code"); if (statusCode == null) { return HttpStatus.INTERNAL_SERVER_ERROR; } return HttpStatus.valueOf(statusCode); } // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // @ExceptionHandler(AuthenticationException.class) // public R handle40001() { // System.out.println("3333"); // return new R(40005, "token1111 invalid"); // } }