GlobalExceptionHandler.java 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148
  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.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.getMessage());
  34. map.put("code", -1);
  35. return map;
  36. }
  37. @ExceptionHandler({AuthenticationException.class})
  38. @ResponseStatus(HttpStatus.UNAUTHORIZED)
  39. @ResponseBody
  40. public Map<String, Object> handleAuthenticationException(AuthenticationException e) {
  41. Map<String, Object> map = new HashMap<>();
  42. map.put("error", e.getMessage());
  43. map.put("code", -1);
  44. return map;
  45. }
  46. @ExceptionHandler(value = TransactionSystemException.class)
  47. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  48. @ResponseBody
  49. public Map<String, Object> serviceExceptionHandler(TransactionSystemException e) {
  50. String message = e.getMessage();
  51. try {
  52. if (e.getCause().getCause() instanceof ConstraintViolationException) {
  53. ConstraintViolationException violationException = (ConstraintViolationException) e.getCause()
  54. .getCause();
  55. message = violationException.getConstraintViolations().stream()
  56. .map(constraintViolation -> constraintViolation.getPropertyPath() + constraintViolation.getMessage())
  57. .collect(Collectors.joining(","));
  58. log.error(message);
  59. }
  60. } catch (Exception ignore) {
  61. }
  62. Map<String, Object> map = new HashMap<>();
  63. map.put("error", message);
  64. map.put("code", -1);
  65. return map;
  66. }
  67. @ExceptionHandler(value = Exception.class)
  68. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  69. @ResponseBody
  70. public Object serviceExceptionHandler(Exception e, HttpServletRequest request) {
  71. log.error(e.getMessage(), e);
  72. if (request.getHeader("Accept").contains("text/html")) {
  73. ModelAndView modelAndView = new ModelAndView("commons/500");
  74. StringWriter out = new StringWriter();
  75. PrintWriter writer = new PrintWriter(out);
  76. e.printStackTrace(writer);
  77. String trace = out.toString();
  78. trace = trace.replaceAll("\n", "<br>");
  79. modelAndView.addObject("trace", trace);
  80. return modelAndView;
  81. } else {
  82. Map<String, Object> map = new HashMap<>();
  83. map.put("error", e.getMessage());
  84. map.put("code", -1);
  85. return map;
  86. }
  87. }
  88. @ExceptionHandler({BindException.class, ConstraintViolationException.class, MethodArgumentNotValidException.class})
  89. @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
  90. @ResponseBody
  91. public Map<String, Object> validateExceptionHandler(Exception e, HttpServletRequest request) {
  92. log.error("请求:{}发生异常:{}", request.getRequestURI(), e);
  93. // 错误信息
  94. StringBuilder sb = new StringBuilder("参数校验失败:");
  95. // 错误信息map
  96. Map<String, String> error = new HashMap<>();
  97. String msg = "";
  98. if (!(e instanceof BindException) && !(e instanceof MethodArgumentNotValidException)) {
  99. for (ConstraintViolation cv : ((ConstraintViolationException) e).getConstraintViolations()) {
  100. msg = cv.getMessage();
  101. sb.append(msg).append(";");
  102. Iterator<Path.Node> it = cv.getPropertyPath().iterator();
  103. Path.Node last = null;
  104. while (it.hasNext()) {
  105. last = (Path.Node) it.next();
  106. }
  107. /*for(last = null; it.hasNext(); last = (Path.Node)it.next()) {
  108. }*/
  109. error.put(last != null ? last.getName() : "", msg);
  110. }
  111. } else {
  112. List<ObjectError> allErrors = null;
  113. if (e instanceof BindException) {
  114. allErrors = ((BindException) e).getAllErrors();
  115. } else {
  116. allErrors = ((MethodArgumentNotValidException) e).getBindingResult().getAllErrors();
  117. }
  118. // 拼接错误信息
  119. for (ObjectError oe : allErrors) {
  120. msg = oe.getDefaultMessage();
  121. sb.append(msg).append(";");
  122. if (oe instanceof FieldError) {
  123. error.put(((FieldError) oe).getField(), msg);
  124. } else {
  125. error.put(oe.getObjectName(), msg);
  126. }
  127. }
  128. }
  129. Map<String, Object> map = new HashMap<>();
  130. map.put("error", "参数校验失败");
  131. map.put("message", sb);
  132. map.put("code", -1);
  133. log.error(e.getMessage());
  134. return map;
  135. }
  136. }