后台接口统一异常处理

对controller中的方法增强

@RestControllerAdvice
public class BaseExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    public Result exception(Exception e){
        e.printStackTrace();
        return new Result(false, StatusCode.ERROR,e.getMessage());
    }
}

当controller中的方法执行出现异常时,就会执行此方法

@RestController
@CrossOrigin
@RequestMapping("/label")
public class LabelController {
    @Autowired
    private LabelService labelService;

    /**
     * 查询所有
     * @return
     */
    @GetMapping
    public Result findAll(){
        //测试异常处理
        int i = 1/0;
        return new Result(true, StatusCode.OK, "查询成功",labelService.findAll());
    }
}

后台接口统一异常处理_第1张图片

你可能感兴趣的:(JavaWeb)