springboot @ControllerAdvice unified exception handling

In the three-tier development architecture, many try catch code blocks are written in the Controller due to the need to handle different exceptions thrown in the Service. It's not elegant

It's so inelegant

 @RequestMapping("userRegister")
    @ResponseBody
    public Object userRegister(String username, String verifycode, String password, String
            confirmPwd, Long recommendorId) throws Exception {
        JsonResult jsonResult = new JsonResult();
        try {
            loginInfoService.userRegister(recommendorId,username, verifycode, password, confirmPwd);
        } catch (DisplayableException e) {
            e.printStackTrace();
            jsonResult.mark(e.getMessage());
        } catch (Exception e) {
            e.printStackTrace();
            jsonResult.mark("Network delay...Please try again later");
        }
        return jsonResult;
    }

Next, use unified exception handling to extract this part of the code (in fact, aop enhancement mode). Use @ ControllerAdvice to strengthen all controllers

@ExceptionHandler specifies the exception to be handled. Use instanceof to handle different exceptions. In addition, you can handle different exceptions according to the returned json or html Controller according to the annotation

The implementation is as follows: code directly:

/**
 * Created by Administrator on 2018/5/3.
 * Enhance all controllers
 */
@ControllerAdvice
public class WSBussinessExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(WSBussinessExceptionHandler.class);
    //Specify Exception type, generally Exception
    @ExceptionHandler(Exception.class)
    public void handler(Exception e, HandlerMethod method, HttpServletResponse resp) throws
            IOException {
        logger.error(e);
        WSResponseVO vo = new WSResponseVO(WSResponseVO.DEFAULT_FALIED_CODE,
                WSResponseVO.DEFAULT_FALIED_MSG);
        if (e instanceof WSBussinessException) {
            //If it is a custom exception, then setmsg. If there are other exceptions, the exception information is wsresponsevo.default menu failed menu MSG
            vo.setMsg(e.getMessage());
        }
        //Judge whether to return json or jump to the page (according to whether there is @ ResponseBody label on the method)
        if (method.getMethodAnnotation(ResponseBody.class) != null) {
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().write(JSON.toJSONString(vo));
        } else {
            resp.sendRedirect("/error/50x.html");
        }
    }
}

After configuration, the Controller doesn't need to write the trycatch code block. It's refreshing

    @RequestMapping("userRegister")
    @ResponseBody
    public Object userRegister(String username, String verifycode, String password, String
            confirmPwd, Long recommendorId) throws Exception {
        JsonResult jsonResult = new JsonResult();
        loginInfoService.userRegister(recommendorId, username, verifycode, password, confirmPwd);
        return jsonResult;
    }

 

Tags: JSON network

Posted on Wed, 27 Nov 2019 10:37:52 -0500 by GrecoClub