Restful接口調用統一異常處理


1.關鍵字解釋

//它是一個Controller增強器,可對controller中被 @RequestMapping注解的方法加一些邏輯處理
@ControllerAdvice
//異常定義
@ExceptionHandler
//返回格式為json,可以使用 @RestControllerAdvice 代替 @ControllerAdvice,這樣在方法上就可以不需要添加 @ResponseBody
@ResponseBody

2.springmvc對於http請求的異常類型

Exception Type

HTTP Status Code 

ConversionNotSupportedException

500 (Internal Server Error) 

HttpMediaTypeNotAcceptableException

 

406 (Not Acceptable)  

HttpMediaTypeNotSupportedException

 

415 (Unsupported Media Type) 

HttpMessageNotReadableException

 

400 (Bad Request) 

HttpMessageNotWritableException

 

 500 (Internal Server Error) 

HttpRequestMethodNotSupportedException

 

405 (Method Not Allowed) 

MissingServletRequestParameterException

400 (Bad Request)  

 

NoSuchRequestHandlingMethodException

 

404 (Not Found)  

 

TypeMismatchException

 

400 (Bad Request)

 



 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

3.代碼

@ControllerAdvice
public class RestfulApiExceptionHandler {
    /**
     * 缺失參數
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = MissingServletRequestParameterException.class)
    @ResponseBody
    public Response missingParameterExceptionHandler(HttpServletRequest request, MissingServletRequestParameterException exception){
        return Response.failure("缺少必要參數,參數名稱為" + exception.getParameterName());
    }

    /**
     * 參數類型不匹配
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler({TypeMismatchException.class})
    @ResponseBody
    public Response typeMismatchExceptionHandler(HttpServletRequest request,TypeMismatchException exception){
        return Response.failure("參數類型不匹配,類型應該為" + exception.getRequiredType());
    }

    /**
     * 請求方法不支持
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = HttpRequestMethodNotSupportedException.class)
    @ResponseBody
    public Response methodNotSupportedExceptionHandler(HttpServletRequest request,HttpRequestMethodNotSupportedException exception){
        return Response.failure("不支持的請求方法");
    }
    /**
     * 其他異常
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Response exceptionHandler(HttpServletRequest request, Exception exception){
        return Response.failure("系統異常");
    }
}

 


免責聲明!

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



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