GlobalExceptionHandler.java 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. package com.izouma.nineth.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.regex.Pattern;
  25. import java.util.stream.Collectors;
  26. @ControllerAdvice
  27. @Slf4j
  28. public class GlobalExceptionHandler {
  29. @ExceptionHandler(value = BusinessException.class)
  30. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  31. @ResponseBody
  32. public Map<String, Object> serviceExceptionHandler(BusinessException e) {
  33. Map<String, Object> map = new HashMap<>();
  34. map.put("error", 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. String message = e.getMessage();
  84. if (Pattern.matches(".*SQL.*constraint.*user_index_phone.*", e.getMessage())) {
  85. message = "手机号已注册";
  86. }
  87. if (Pattern.matches(".*SQL.*constraint.*username.*", e.getMessage())) {
  88. message = "用户名已存在";
  89. }
  90. Map<String, Object> map = new HashMap<>();
  91. map.put("error", message);
  92. map.put("code", -1);
  93. return map;
  94. }
  95. }
  96. @ExceptionHandler({BindException.class, ConstraintViolationException.class, MethodArgumentNotValidException.class})
  97. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  98. @ResponseBody
  99. public Map<String, Object> validateExceptionHandler(Exception e, HttpServletRequest request) {
  100. log.error("请求:{}发生异常:{}", request.getRequestURI(), e);
  101. // 错误信息
  102. StringBuilder sb = new StringBuilder("参数校验失败:");
  103. // 错误信息map
  104. Map<String, String> error = new HashMap<>();
  105. String msg = "";
  106. if (!(e instanceof BindException) && !(e instanceof MethodArgumentNotValidException)) {
  107. for (ConstraintViolation cv : ((ConstraintViolationException) e).getConstraintViolations()) {
  108. msg = cv.getMessage();
  109. sb.append(msg).append(";");
  110. Iterator<Path.Node> it = cv.getPropertyPath().iterator();
  111. Path.Node last = null;
  112. while (it.hasNext()) {
  113. last = (Path.Node) it.next();
  114. }
  115. /*for(last = null; it.hasNext(); last = (Path.Node)it.next()) {
  116. }*/
  117. error.put(last != null ? last.getName() : "", msg);
  118. }
  119. } else {
  120. List<ObjectError> allErrors = null;
  121. if (e instanceof BindException) {
  122. allErrors = ((BindException) e).getAllErrors();
  123. } else {
  124. allErrors = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors();
  125. }
  126. // 拼接错误信息
  127. for (ObjectError oe : allErrors) {
  128. msg = oe.getDefaultMessage();
  129. sb.append(msg).append(";");
  130. if (oe instanceof FieldError) {
  131. error.put(((FieldError) oe).getField(), msg);
  132. } else {
  133. error.put(oe.getObjectName(), msg);
  134. }
  135. }
  136. }
  137. Map<String, Object> map = new HashMap<>();
  138. map.put("error", "参数校验失败");
  139. map.put("message", sb);
  140. map.put("code", -1);
  141. log.error(e.getMessage());
  142. return map;
  143. }
  144. }