对于业务比较复杂的接口,可能存在方法嵌套,每个方法都可能会报错,出现异常,那么需要把异常信息返回给接口调用者,如何实现呢?
 (1)捕获异常进行处理,不返回
 controller代码
@AllArgsConstructor
@RestController
@Slf4j
public class DemoController {
    private IDemoService demoService;
    @GetMapping("exceptionTest")
    public Result exceptionTest(Integer integer1, Integer integer2) {
        int a = demoService.exceptionTest(integer1, integer2);
        return Result.success(a);
    }
}
 
service代码
@Service
public class DemoServiceImpl implements IDemoService {
    @Override
    public int exceptionTest(Integer integer1, Integer integer2) {
        Integer result = 0;
        try {
            result = integer2/integer1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
}
 
业务代码出现异常,可进行捕获,捕获之后能解决,则处理,如不能处理,则需要抛出异常
 抛出异常的2种方式:
 第一种方法抛出Exception,第二钟方法抛出RuntimeException
 Exception :受检查的异常,这种异常是强制我们catch或throw的异常。你遇到这种异常必须进行catch或throw,如果不处理,编译器会报错。比如:IOException。
RuntimeException:运行时异常,这种异常我们不需要处理,完全由虚拟机接管。比如我们常见的NullPointerException,我们在写程序时不会进行catch或throw。


 对service的方法抛出的异常,调用时必须进行捕获处理或者声明抛出
 
 controller捕获异常,可以处理或者继续抛出

 抛出异常,告知调用者报错信息,有些因操作不当或者配置问题,可进行排查。
 一般不在被调用的方法捕获异常,抛出异常,调用者捕获异常进行处理,如果无法处理,继续抛出,直到最顶层的调用者进行处理。
 Springboot框架写接口时,建议在controller的方法里面捕获异常并处理。



















