• 异常捕获设置HTTPStatus


    第一步:创建一个异常类

    package com.payease.exception;
    
    /**
     * @Created By liuxiaoming
     * @CreateTime 2017/12/12 下午5:02
     **/
    public class ResponseBankException extends RuntimeException {
    }

    第二步:在业务中抛出异常

    第三步:对该异常进行捕获并设置HTTPstatus状态码 :例如设置403

    package com.payease.handler;
    
    import com.payease.VO.ResultVO;
    import com.payease.config.ProjectUrlConfig;
    import com.payease.exception.ResponseBankException;
    import com.payease.exception.SellException;
    import com.payease.exception.SellerAuthorizeException;
    import com.payease.utils.ResultVOUtil;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.http.HttpStatus;
    import org.springframework.web.bind.annotation.ControllerAdvice;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.ResponseStatus;
    import org.springframework.web.servlet.ModelAndView;
    
    /**
     * 异常捕获类
     * @Created By liuxiaoming
     * @CreateTime 2017/12/8 上午10:54
     **/
    @ControllerAdvice
    public class SellerExceptionHandler {
    
        @Autowired
        private ProjectUrlConfig projectUrlConfig;
        //拦截登录异常
        //http://sell.natapp4.cc/sell/wechat/qrAuthorize?returnUrl=http://sell.natapp4.cc/sell/seller/login
        @ExceptionHandler(value= SellerAuthorizeException.class)
        public ModelAndView handlerAuthorizeException(){
            return new ModelAndView("redirect:".concat("/seller/loginException"));
    //                .concat(projectUrlConfig.getWechatOpenAuthorize())
    //                .concat("/sell/wechat/qrAuthorize")
    //                .concat("?returnUrl=")
    //                .concat(projectUrlConfig.getSell())
    //                .concat("/sell/seller/login"));
        }
    
    
        @ExceptionHandler(value = SellException.class)
        @ResponseBody
        public ResultVO handlerSellerException(SellException e){
            return ResultVOUtil.error(e.getCode(),e.getMessage());
        }
    
        @ExceptionHandler(value = ResponseBankException.class)
        @ResponseStatus(HttpStatus.FORBIDDEN)
        public void handlerResponseBankException(){
    
        }
    }

    第四步:启动项目,并进行postman提交

  • 相关阅读:
    [Javascript] Prototype Pattern
    [Typescript] tsexpecterror
    [React] Compound Pattern
    [React] SWR for data fetching
    [Javascript] Factory pattern vs Class instance
    [Typescript] Only Type import or export
    AcWing 1113. 红与黑
    AcWing 178 第K短路
    AcWing 190.字串变换
    AcWing 165 小猫爬山
  • 原文地址:https://www.cnblogs.com/liuxiaoming123/p/8028770.html
Copyright © 2020-2023  润新知