ExceptionController.java 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. package com.fd.controller;
  2. import com.fd.util.R;
  3. import org.apache.shiro.ShiroException;
  4. import org.apache.shiro.authc.AuthenticationException;
  5. import org.apache.shiro.authc.IncorrectCredentialsException;
  6. import org.apache.shiro.authc.UnknownAccountException;
  7. import org.apache.shiro.authz.UnauthorizedException;
  8. import org.springframework.http.HttpStatus;
  9. import org.springframework.web.bind.annotation.ExceptionHandler;
  10. import org.springframework.web.bind.annotation.ResponseStatus;
  11. import org.springframework.web.bind.annotation.RestControllerAdvice;
  12. import javax.servlet.http.HttpServletRequest;
  13. /**
  14. * 统一捕捉异常,自定义返回参数
  15. * 这里只可以捕获controller层的异常。
  16. */
  17. @RestControllerAdvice
  18. public class ExceptionController {
  19. // 捕捉shiro的异常
  20. @ResponseStatus(HttpStatus.UNAUTHORIZED)
  21. @ExceptionHandler(ShiroException.class)
  22. public R handle401(ShiroException e) {
  23. return new R(40002, e.getMessage());
  24. }
  25. // 捕捉UnauthorizedException
  26. @ResponseStatus(HttpStatus.UNAUTHORIZED)
  27. @ExceptionHandler(UnauthorizedException.class)
  28. public R handle401() {
  29. return new R(40003, "Unauthorized");
  30. }
  31. // 捕捉其他所有异常
  32. @ExceptionHandler(Exception.class)
  33. @ResponseStatus(HttpStatus.BAD_REQUEST)
  34. public R globalException(HttpServletRequest request, Throwable ex) {
  35. return new R(getStatus(request).value(), ex.getMessage());
  36. }
  37. private HttpStatus getStatus(HttpServletRequest request) {
  38. Integer statusCode = (Integer) request.getAttribute("javax.servlet.error.status_code");
  39. if (statusCode == null) {
  40. return HttpStatus.INTERNAL_SERVER_ERROR;
  41. }
  42. return HttpStatus.valueOf(statusCode);
  43. }
  44. // @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  45. // @ExceptionHandler(AuthenticationException.class)
  46. // public R handle40001() {
  47. // System.out.println("3333");
  48. // return new R(40005, "token1111 invalid");
  49. // }
  50. }