springboot + 全局异常处理

ControllerAdvice

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.HashMap;
import java.util.Map;
@ControllerAdvice
public class MayiktExceptionHandler {

  @ExceptionHandler({RuntimeException.class})
  @ResponseBody
  public Map<String,String> exceptionHandler(){
    HashMap<String,String > objectObjectHashMap=new HashMap<>();
    objectObjectHashMap.put("respCode","500");
    objectObjectHashMap.put("respMsg","系统错识");
    return objectObjectHashMap;
  }
}


import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

  @RestController
  public class TestContoller {

    @RequestMapping("/test1")
    public String test1(String username,Integer age){
      int j=1/age;
      return "error";
    }

}

原文地址:https://www.cnblogs.com/smallfa/p/13650148.html