一、背景在编写程序的过程中,程序中随时可能出现各种异常,那么我们如何优雅地处理各种异常呢?二、需求1、拦截系统中的一些异常,返回自定义响应。比如系统出现HttpRequestMethodNotSupportedException,我们需要返回如下信息。HTTP状态码:return405{code:自定义异常代码,message:错误信息}2、实现自定义异常的拦截,拦截自己写的BizException3、编写一些基本的异常代码1、引入jar包org.springframework.bootspring-boot-starter-weborg.springframework.boot春天-boot-starter-validation注:spring-boot-starter-validation的引入是对请求中的参数进行校验,当参数不满足时抛出异常.2.定义自定义异常publicclassBizExceptionextendsRuntimeException{publicBizException(){}publicBizException(Stringmessage){super(message);}publicBizException(Stringmessage,Throwablecause){super(message,cause);}publicBizException(Throwablecause){super(cause);}publicBizException(Stringmessage,Throwablecause,booleanenableSuppression,booleanwritableStackTrace){super(message,cause,enableSuppression,writableStackTrace);}}3.写一个简单的控制层@RestController@RequestMapping("exception")publicclassExceptionTestController{staticclassReq{@NotBlankpublicStringpassword;}@PostMapping("password")publicStringcheckPassword(@Validated@RequestBodyReqreq){if(Objects.equals(req.password,"exception")){thrownewBizException("传递的密码是异常字符串");}返回“当前Password,password:"+req.password;}}说明提供一个/exception/passwordapi,需要传递一个password参数。1.当不传递password参数时,会抛出一个MethodArgumentNotValidException。2.当password传递异常参数,会抛出BizException。4.测试1.不传递password参数的响应是什么?1.使用默认的DefaultHandlerExceptionResolver来处理这个类,DefaultHandlerExceptionResolver默认是自动配置的。从上图可以看出有一个默认字段的返回值2.使用ResponseEntityExceptionHandler处理1.编写异常处理代码-使用默认逻辑MethodArgumentNotValidExceptionex,HttpHeadersheaderscustomquereturn){returnherestatus,HttpWebStatussuper.handleMethodArgumentNotValid(ex,headers,status,request);}}}可以看到handleMethodArgumentNotValid方法是直接调用父类的方法,即使用默认的处理方式。从上图可以看出返回值为空2.编写异常处理代码-返回值返回自定义内容,WebRequestrequest){//这里自定义返回值returnsuper.handleMethodArgumentNotValid(ex,headers,status,request);}@OverrideprotectedResponseEntity