[关闭]
@PheonixHkbxoic 2018-03-08T08:41:41.000000Z 字数 3080 阅读 1050

SpringBoot添加全局异常处理器

SpringBoot



1.Application.yml中开启mvc异常处理

  1. spring:
  2. mvc:
  3. throw-exception-if-no-handler-found: true

2.启动类添加注解@EnableWebMvc

  1. @SpringBootApplication
  2. @MapperScan("cn.pheker.springbootdemo.mapper")
  3. @ServletComponentScan
  4. @EnableTransactionManagement
  5. @EnableWebMvc
  6. public class WebApplication {
  7. public static void main(String[] args) {
  8. SpringApplication.run(WebApplication.class, args);
  9. }
  10. }

3.全局处理类

  1. package cn.pheker.springbootdemo.config;
  2. import cn.pheker.springbootdemo.utils.Result;
  3. import cn.pheker.springbootdemo.utils.UtilException;
  4. import cn.pheker.springbootdemo.utils.UtilResult;
  5. import org.slf4j.Logger;
  6. import org.slf4j.LoggerFactory;
  7. import org.springframework.validation.FieldError;
  8. import org.springframework.web.HttpRequestMethodNotSupportedException;
  9. import org.springframework.web.bind.MethodArgumentNotValidException;
  10. import org.springframework.web.bind.MissingServletRequestParameterException;
  11. import org.springframework.web.bind.annotation.ControllerAdvice;
  12. import org.springframework.web.bind.annotation.ExceptionHandler;
  13. import org.springframework.web.bind.annotation.ResponseBody;
  14. import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
  15. import org.springframework.web.servlet.NoHandlerFoundException;
  16. import javax.servlet.http.HttpServletRequest;
  17. import java.util.ArrayList;
  18. import java.util.List;
  19. /**
  20. * <pre>
  21. * author cn.pheker
  22. * date 2018/3/7 14:25
  23. * email 1176479642@qq.com
  24. * desc 全局异常处理器
  25. *
  26. * </pre>
  27. */
  28. @ControllerAdvice
  29. public class GlobalExceptionHandler {
  30. private Logger logger = LoggerFactory.getLogger(this.getClass());
  31. @ExceptionHandler(Exception.class)
  32. @ResponseBody
  33. public Result<?> jsonErrorHandler(HttpServletRequest request, Exception e) {
  34. Result result;
  35. //无此页面或地址
  36. if(e instanceof NoHandlerFoundException) {//404
  37. return UtilResult.fail(UtilResult.TYPE.NOT_FOUND, request.getRequestURI());
  38. }else if(e instanceof HttpRequestMethodNotSupportedException){
  39. return UtilResult.fail(UtilResult.TYPE.METHOD_NOT_SUPPORTED, request.getRequestURI());
  40. //缺少参数
  41. }else if(e instanceof MissingServletRequestParameterException) {
  42. result = UtilResult.fail(UtilResult.TYPE.PARAMETER_MISS, e.getMessage());
  43. //参数类型不对或无法转换
  44. }else if(e instanceof MethodArgumentTypeMismatchException){
  45. MethodArgumentTypeMismatchException matme = (MethodArgumentTypeMismatchException) e;
  46. result = UtilResult.fail(UtilResult.TYPE.PARAMETER_NOT_MATCH,matme.getMessage());
  47. }else if(e instanceof MethodArgumentNotValidException){//参数校验
  48. List<Result<String>> errorResults = new ArrayList<Result<String>>();
  49. for (FieldError fieldError : ((MethodArgumentNotValidException) e).getBindingResult().getFieldErrors()) {
  50. errorResults.add(UtilResult.fail(Integer.parseInt(fieldError.getCode()),fieldError.getDefaultMessage(),
  51. fieldError.getField()+fieldError.getRejectedValue()));
  52. }
  53. return UtilResult.fail(500,e.getMessage(),errorResults);
  54. }else{
  55. result = UtilException.getResult(request, e.getMessage());
  56. logger.debug(result.toString());
  57. }
  58. e.printStackTrace();
  59. logger.error(e.getMessage());
  60. return result;
  61. }
  62. }

以上是采用注解的方法实现的,@ControllerAdvice表示处理Controller,
@ExceptionHandler指明要处理的异常和使用当前方法处理该异常
@ResponseBody表明返回json,不写表明反回页面或ModelAndView

4.也可以采用其它的方式来实现

添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注