異常捕獲設置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提交

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM