这里解决之前留下来的问题,当程序没有正常返回时候
就是程序由于运行时异常导致的结果,有些异常我们可,能无法提前预知,不能正常走到我们return的R对象返回。这个时候该如何处理
在SpringBoot中,可以使用@ControllerAdvice注解来启用全局异常处理。通过使用@ControllerAdvice注解,可以捕获应用程序中的所有异常,从而实现统一的异常处理。如果要自定义异常处理方法,可以使用@ExceptionHandler注解,并指定要捕获的异常类型。这样就可以对指定的异常进行统一的处理。因此,通过@ControllerAdvice和@ExceptionHandler注解的组合,可以实现全局的异常处理。
代码示列
1package cn.soboys.springbootrestfulapi.common.exception; 2 3 4import cn.soboys.springbootrestfulapi.common.resp.R; 5import cn.soboys.springbootrestfulapi.common.resp.ResultCodeEnum; 6import org.springframework.context.support.DefaultMessageSourceResolvable; 7import org.springframework.validation.BindException; 8import org.springframework.web.bind.annotation.ExceptionHandler; 9import org.springframework.web.bind.annotation.ResponseBody; 10import org.springframework.web.bind.annotation.RestControllerAdvice; 11 12import javax.validation.ConstraintViolation; 13import javax.validation.ConstraintViolationException; 14import java.util.stream.Collectors; 15 16 17/** 18 * @author 公众号 程序员三时 19 * @version 1.0 20 * @date 2023/4/29 00:21 21 * @webSite https://github.com/coder-amiao 22 * 统一异常处理器 23 */ 24@RestControllerAdvice 25public class GlobalExceptionHandler { 26 27 /** 28 * 通用异常处理方法 29 **/ 30 @ExceptionHandler(Exception.class) 31 @ResponseBody 32 public R error(Exception e) { 33 e.printStackTrace(); 34 return R.setResult(ResultCodeEnum.INTERNAL_SERVER_ERROR); 35 } 36 37 /** 38 * 指定异常处理方法 39 **/ 40 @ExceptionHandler(NullPointerException.class) 41 @ResponseBody 42 public R error(NullPointerException e) { 43 e.printStackTrace(); 44 return R.setResult(ResultCodeEnum.NULL_POINT); 45 } 46 47 48 /** 49 * 处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常 50 */ 51 @ExceptionHandler(BindException.class) 52 @ResponseBody 53 public R BindExceptionHandler(BindException e) { 54 String message = e.getBindingResult().getAllErrors().stream().map(DefaultMessageSourceResolvable::getDefaultMessage).collect(Collectors.joining()); 55 return R.failure().code(ResultCodeEnum.PARAM_ERROR.getCode()).message(message); 56 } 57 58 /** 59 * 处理Get请求中 使用@Validated 验证路径中 单个参数请求失败抛出异常 60 * @param e 61 * @return 62 */ 63 @ExceptionHandler(ConstraintViolationException.class) 64 public R ConstraintViolationExceptionHandler(ConstraintViolationException e) { 65 String message = e.getConstraintViolations().stream().map(ConstraintViolation::getMessage).collect(Collectors.joining()); 66 return R.failure().code(ResultCodeEnum.PARAM_ERROR.getCode()).message(message); 67 } 68 69 70 71 /** 72 * 自定义异常处理方法 73 * 74 * @param e 75 * @return 76 */ 77 @ExceptionHandler(BusinessException.class) 78 @ResponseBody 79 public R error(BusinessException e) { 80 e.printStackTrace(); 81 return R.failure().message(e.getMessage()).code(e.getCode()); 82 } 83 84} 85
异常处理,能够减少代码的重复度和复杂度,有利于代码的维护,并且能够快速定位到BUG,大大提高我们的开发效率。
通过@ControllerAdvice 返回对应错误视图页面,@RestControllerAdvice 返回json 格式的错误api,也可以通过@ControllerAdvice 在方法上加上@ResponseBody返回对应json格式, 类比,controller中返回是一样的
这样暂时解决了,我们上一片文章留下问题

思考
其实这样写,还是不够完美,我们知道我们错误类型有很多种,参数错误也有很多,参数校验还没有达到框架级别,
例如这个是阿里云ECS错误
1{ 2 "RequestId": "5E571499-13C5-55E3-9EA6-DEFA0DBC85E4", 3 "HostId": "ecs-cn-hangzhou.aliyuncs.com", 4 "Code": "InvalidOperation.NotSupportedEndpoint", 5 "Message": "The specified endpoint can't operate this region. Please use API DescribeRegions to get the appropriate endpoint, or upgrade your SDK to latest version.", 6 "Recommend": "https://next.api.aliyun.com/troubleshoot?q=InvalidOperation.NotSupportedEndpoint&product=Ecs" 7}
这是新浪api的
1{ 2 "request": "/statuses/home_timeline.json", 3 "error_code": "20502", 4 "error": "Need you follow uid." 5}
或者说这样
1{ 2 "result": false, 3 "error": {"code": 102, "message": "Validation failed: Wrong NAME."} 4}
我们如何在进一步改进呢,
下一篇文章会继续分享,留下你的思考
准备从零做一套自己的开发脚手架模板 ,关注公众 程序员三时
