在有参数校验的基础上,新建异常处理类:(@ControllerAdvice("com.store.score.rpc.web")控制访问提示信息范围)
package com.store.score.util;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import javax.validation.UnexpectedTypeException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
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 com.store.score.model.response.MapResModel;
@ResponseBody
@ControllerAdvice("com.store.score.rpc.web")
public class ApiExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(ApiExceptionHandler.class);
/**
* @param exception UnexpectedTypeException
* @param response
* @return
*/
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(UnexpectedTypeException.class)
public MapResModel unexpectedType(UnexpectedTypeException exception, HttpServletResponse response){
MapResModel mapResModel = new MapResModel();
LOGGER.error("校验方法太多,不确定合适的校验方法。", exception);
mapResModel.failure("校验方法太多,不确定合适的校验方法。");
return mapResModel;
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(HttpMessageNotReadableException.class)
public MapResModel messageNotReadable(HttpMessageNotReadableException exception, HttpServletResponse response){
MapResModel mapResModel = new MapResModel();
LOGGER.error("请求参数不匹配。", exception);
mapResModel.failure("请求参数不匹配:"+exception.getMessage());
return mapResModel;
}
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ExceptionHandler(Exception.class)
public MapResModel ex(MethodArgumentNotValidException exception, HttpServletResponse response){
MapResModel mapResModel = new MapResModel();
LOGGER.error("请求参数不合法。", exception);
Map<String, String> map = getErrors(exception.getBindingResult());
mapResModel.setData(map);
mapResModel.failure("请求参数不合法。");
return mapResModel;
}
private Map<String, String> getErrors(BindingResult result) {
Map<String, String> map = new HashMap<>();
List<FieldError> list = result.getFieldErrors();
for (FieldError error : list) {
map.put(error.getField(), error.getDefaultMessage());
}
return map;
}
}