@ControllerAdvice+@ExceptionHandler全局异常捕获,并格式化给前端

我现在做的是web项目,当后台发生错误的时候,为了方便前端能够查看到错误,需要使用try{}catch{}方法,但是这样写太麻烦了,我们可以使用@ControllerAdvice+@ExceptionHandler进行全局异常的定义,例如:

/**
 * 业务处理异常
 */
public class BusinessHandlingException extends RuntimeException {

    private static final long serialVersionUID = -8999510391137855828L;

    public BusinessHandlingException(String code, String message) {
        super(code + SPLIT_MARK + message);
    }

}
    @Authorization
    @RequestMapping(value = "test", method = RequestMethod.POST)
    public Object test(@RequestBody JSONObject parameter) {
        String phoneNumber = getNotBlankString(parameter, "phoneNumber");
        if (!ValidateUtils.phoneNumber(phoneNumber)) {
            throw new BusinessHandlingException("phoneNumber-parameter-error", "手机号格式不正确");
        }
        return ResponseData.getResult(true);
    }
@ControllerAdvice(annotations = RestController.class)
public class ExceptionAdvice {
 /**
     * 业务异常
     */
    @CrossOrigin
    @ResponseBody
    @ExceptionHandler(BusinessHandlingException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseEntity> businessHandlingExceptionHandle(BusinessHandlingException e) {
        HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        response.setHeader("Access-Control-Allow-Origin", "*");
        return ResponseEntity.ok(ResponseData.getExceptionResult(CODE_40007, MESSAGE_40007, e.getMessage()));
    }
}

 

你可能感兴趣的:(框架)