GlobalExceptionHandler.java 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149
  1. package com.izouma.awesomeAdmin.exception;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.http.HttpStatus;
  4. import org.springframework.transaction.TransactionSystemException;
  5. import org.springframework.validation.BindException;
  6. import org.springframework.validation.FieldError;
  7. import org.springframework.validation.ObjectError;
  8. import org.springframework.web.bind.MethodArgumentNotValidException;
  9. import org.springframework.web.bind.annotation.ControllerAdvice;
  10. import org.springframework.web.bind.annotation.ExceptionHandler;
  11. import org.springframework.web.bind.annotation.ResponseBody;
  12. import org.springframework.web.bind.annotation.ResponseStatus;
  13. import org.springframework.web.servlet.ModelAndView;
  14. import javax.servlet.http.HttpServletRequest;
  15. import javax.validation.ConstraintViolation;
  16. import javax.validation.ConstraintViolationException;
  17. import javax.validation.Path;
  18. import java.io.PrintWriter;
  19. import java.io.StringWriter;
  20. import java.util.HashMap;
  21. import java.util.Iterator;
  22. import java.util.List;
  23. import java.util.Map;
  24. import java.util.stream.Collectors;
  25. @ControllerAdvice
  26. @Slf4j
  27. public class GlobalExceptionHandler {
  28. @ExceptionHandler(value = BusinessException.class)
  29. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  30. @ResponseBody
  31. public Map<String, Object> serviceExceptionHandler(BusinessException e) {
  32. Map<String, Object> map = new HashMap<>();
  33. map.put("error", e.getError());
  34. map.put("message", e.getMessage());
  35. map.put("code", -1);
  36. return map;
  37. }
  38. @ExceptionHandler({AuthenticationException.class})
  39. @ResponseStatus(HttpStatus.UNAUTHORIZED)
  40. @ResponseBody
  41. public Map<String, Object> handleAuthenticationException(AuthenticationException e) {
  42. Map<String, Object> map = new HashMap<>();
  43. map.put("error", e.getMessage());
  44. map.put("code", -1);
  45. return map;
  46. }
  47. @ExceptionHandler(value = TransactionSystemException.class)
  48. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  49. @ResponseBody
  50. public Map<String, Object> serviceExceptionHandler(TransactionSystemException e) {
  51. String message = e.getMessage();
  52. try {
  53. if (e.getCause().getCause() instanceof ConstraintViolationException) {
  54. ConstraintViolationException violationException = (ConstraintViolationException) e.getCause()
  55. .getCause();
  56. message = violationException.getConstraintViolations().stream()
  57. .map(constraintViolation -> constraintViolation.getPropertyPath() + constraintViolation.getMessage())
  58. .collect(Collectors.joining(","));
  59. log.error(message);
  60. }
  61. } catch (Exception ignore) {
  62. }
  63. Map<String, Object> map = new HashMap<>();
  64. map.put("error", message);
  65. map.put("code", -1);
  66. return map;
  67. }
  68. @ExceptionHandler(value = Exception.class)
  69. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  70. @ResponseBody
  71. public Object serviceExceptionHandler(Exception e, HttpServletRequest request) {
  72. log.error(e.getMessage(), e);
  73. if (request.getHeader("Accept").contains("text/html")) {
  74. ModelAndView modelAndView = new ModelAndView("commons/500");
  75. StringWriter out = new StringWriter();
  76. PrintWriter writer = new PrintWriter(out);
  77. e.printStackTrace(writer);
  78. String trace = out.toString();
  79. trace = trace.replaceAll("\n", "<br>");
  80. modelAndView.addObject("trace", trace);
  81. return modelAndView;
  82. } else {
  83. Map<String, Object> map = new HashMap<>();
  84. map.put("error", e.getMessage());
  85. map.put("code", -1);
  86. return map;
  87. }
  88. }
  89. @ExceptionHandler({BindException.class, ConstraintViolationException.class, MethodArgumentNotValidException.class})
  90. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  91. @ResponseBody
  92. public Map<String, Object> validateExceptionHandler(Exception e, HttpServletRequest request) {
  93. log.error("请求:{}发生异常:{}", request.getRequestURI(), e);
  94. // 错误信息
  95. StringBuilder sb = new StringBuilder("参数校验失败:");
  96. // 错误信息map
  97. Map<String, String> error = new HashMap<>();
  98. String msg = "";
  99. if (!(e instanceof BindException) && !(e instanceof MethodArgumentNotValidException)) {
  100. for (ConstraintViolation cv : ((ConstraintViolationException) e).getConstraintViolations()) {
  101. msg = cv.getMessage();
  102. sb.append(msg).append(";");
  103. Iterator<Path.Node> it = cv.getPropertyPath().iterator();
  104. Path.Node last = null;
  105. while (it.hasNext()) {
  106. last = (Path.Node) it.next();
  107. }
  108. /*for(last = null; it.hasNext(); last = (Path.Node)it.next()) {
  109. }*/
  110. error.put(last != null ? last.getName() : "", msg);
  111. }
  112. } else {
  113. List<ObjectError> allErrors = null;
  114. if (e instanceof BindException) {
  115. allErrors = ((BindException) e).getAllErrors();
  116. } else {
  117. allErrors = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors();
  118. }
  119. // 拼接错误信息
  120. for (ObjectError oe : allErrors) {
  121. msg = oe.getDefaultMessage();
  122. sb.append(msg).append(";");
  123. if (oe instanceof FieldError) {
  124. error.put(((FieldError) oe).getField(), msg);
  125. } else {
  126. error.put(oe.getObjectName(), msg);
  127. }
  128. }
  129. }
  130. Map<String, Object> map = new HashMap<>();
  131. map.put("error", "参数校验失败");
  132. map.put("message", sb);
  133. map.put("code", -1);
  134. log.error(e.getMessage());
  135. return map;
  136. }
  137. }