1. 程式人生 > 實用技巧 >Restful介面呼叫統一異常處理

Restful介面呼叫統一異常處理

1.關鍵字解釋

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

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

Exception Type

HTTP StatusCode

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("系統異常"); } }