统一异常处理

简要描述:

  • 在web层controller业务代码中,一般不要处理任何异常,将异常完全跑出,由ExceptionHandler统一处理

example1:

根据不同的异常类型,区分处理,最终返回前端code,msg
AppBizException,业务异常,根据返回的异常码从配置了获得msg
Exception,error日志,大部分非App异常说明程序发生未知异常,需要打印error日志,通过邮件报警后续跟踪处理
  @ControllerAdvice("com.ly.fn.biz.ins.miniapp")
@Component
public class CommonAdvice {

    private static final Logger LOG = LoggerFactory.getLogger(CommonAdvice.class);

    private static final String defaultMsg = "正在为您努力加载,请稍后再试";

    @Rpcwired
    private DictService dictService;

    @Autowired
    private NeedJumpDecider decider;


    @ExceptionHandler
    @ResponseBody
    public JsonResp exception(HttpServletRequest request, Exception ex, HttpServletResponse response)
            throws IOException {
        // 根据不同错误转向不同页面
        LOG.error("systemException,where memberId={}", ex);
        return JsonResp.resp(JsonResp.FAIL, defaultMsg, new BaseResponse());
    }

    @ExceptionHandler
    @ResponseBody
    public JsonResp exception(HttpServletRequest request, Error ex, HttpServletResponse response)
            throws IOException {
        // 根据不同错误转向不同页面
        LOG.error("systemException", ex);
        return JsonResp.resp(JsonResp.FAIL, defaultMsg, new BaseResponse());
    }

    @ExceptionHandler
    @ResponseBody
    public JsonResp exception(HttpServletRequest request, BindException ex, HttpServletResponse response)
            throws IOException {
        // 根据不同错误转向不同页面
        LOG.error("bindException,{}", JSON.toJSONString(ex.getAllErrors()), ex);
        return JsonResp.resp(JsonResp.PARAM_FAIL, "paramError", new BaseResponse());
    }

你可能感兴趣的:(统一异常处理)