springMVC统一处理异常信息  
 
   
   
  通过抛出异常,返回json提示信息。
   
  1.在项目中模拟一个异常。
   
   
  		try {
			int i=1/0;
		} catch (Exception e){
			//自定义异常,存储提示信息,防止错误信息丢失
			throw new CustomException("除数不能为零",e);
		}
  
2.自定义异常。 
  public class CustomException extends RuntimeException {
	public CustomException(String message, Throwable cause) {
		super(message, cause);
	}
	public CustomException() {
	}
}
   3.在spring能扫描到的包内,(可以对全部的controller进行CustomException异常捕获)
   
  @ControllerAdvice
public class RunTime {
	@ExceptionHandler(CustomException.class)
	public @ResponseBody Map<String,Object> demo(NativeWebRequest request, CustomException e){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("resCode", 1);
		map.put("msg", e.getMessage());
		//记录日志--- 略
		return map;
 }} 或者:在controller中:(只能捕获本controller中的CustomException异常信息)
   
  	@ExceptionHandler(CustomException.class)
	public @ResponseBody Map<String,Object> demo(NativeWebRequest request, CustomException e){
		Map<String,Object> map=new HashMap<String,Object>();
		map.put("resCode", 1);
		map.put("msg", e.getMessage());
		return map;
	}
   4.返回信息:
   
  {
  "resCode": 1,
  "msg": "除数不能为零"
}
   
   
   
   
   
   
   
   
   
   
   
  
                
        
    
 
                    转载请注明原文地址: https://ju.6miu.com/read-675736.html