1、编写自定义异常类:
2、统一异常拦截
/** * @author * @version 1.0.0 * @ClassName ControllerHanderException.java * @Description 统一拦截自定义异常获取code和msg返回给前端 * @createTime 2022年02月09日 15:40:00 */ @ControllerAdvice public class ControllerHanderException { @ExceptionHandler(BaseException.class) @ResponseBody @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) //在这个方法里定义我们需要返回的格式 public WrappedResult handleUserNotExistException(BaseException ex){ return WrappedResult.failedWrappedResult(ex.getCode(),ex.getMsg()); } }
3、controller层抛出自定义异常。
public WrappedResult getData(@RequestBody @Validated KmOsboardCardDTO kmOsboardCardDTO){ try { Map<String,Object> wrappedResult =iKmOsboardService.getList(kmOsboardCardDTO); return WrappedResult.successWrapedResult(wrappedResult); } catch (Exception e) { String errorMessage = "查询异常"; throw new BaseException(errorMessage,e); } }
4、结果:
{ "code": "500", "msg": "查询异常", "data": null }