統一異常處理類
package com.wdcloud.categoryserver.common.exception; import com.wdcloud.categoryserver.common.constant.CodeConstants; import com.wdcloud.categoryserver.common.entity.BaseView; import org.springframework.http.converter.HttpMessageNotReadableException; 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.RestController; import org.springframework.web.multipart.support.MissingServletRequestPartException; import javax.servlet.http.HttpServletRequest; /** * @describe: 全局異常處理 * @author: zhuchunwang * @date: 2018/5/29 17:40 * @version: 1.0 */ @ControllerAdvice(annotations = {RestController.class}) public class GlobalExceptionHandler { /** * 默認未知異常 * @param req * @param e * @return * @throws Exception */ @ExceptionHandler(value = Exception.class) @ResponseBody public BaseView defaultErrorHandler(HttpServletRequest req, Exception e) throws Exception { e.printStackTrace(); return new BaseView(CodeConstants.SYSTEM_EXCEPTION,CodeConstants.SYSTEM_EXCEPTION_MSG); } /** * 參數異常 * @param req * @param e * @return * @throws Exception */ @ExceptionHandler(value = {HttpMessageNotReadableException.class, MissingServletRequestPartException.class}) @ResponseBody public BaseView httpMessageNotReadableExceptionErrorHandler(HttpServletRequest req, Exception e) throws Exception { e.printStackTrace(); return new BaseView(CodeConstants.PARAMETER_ERROR,CodeConstants.PARAMETER_ERROR_MSG); } }
一個參數時這樣寫
@ExceptionHandler(value = HttpMessageNotReadableException.class)
多個參數時這樣寫
@ExceptionHandler(value = {HttpMessageNotReadableException.class, MissingServletRequestPartException.class})