在openfeign客户端如何获取到服务端抛出的准确异常信息??
相关参考
背景引入
浏览器直接访问Spring的Restful接口(最普遍、简单的访问)
示例
直接在controller层抛出一个异常:观察浏览器接收到的准确信息是什么 ?
Controller代码如下:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class ClassForTest {
Logger logger = LoggerFactory.getLogger(this.getClass());
@GetMapping("/ex/handler")
public String testExceptionHandler() throws Exception {
throw new Exception("抛出了异常哈。。。");
// int x = 3/0;
// return "nothing";
}
}
浏览器返回:
上图的返回信息是SpringMVC默认处理方式,如果服务端抛出了异常默认就会返回上述信息!
那么,如何获取到自己想要的或者服务端返回的真实异常信息!!
编写自定义异常处理即可获取到想要的真实异常信息,如下:
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
@ControllerAdvice
public class CustomExceptionHandler {
/**
* 全局异常处理
* @param e
* @param response
* @return
*/
@ExceptionHandler(value =Exception.class)
@ResponseBody
public TestEntity myExHandler(Exception e,HttpServletResponse response) {
TestEntity te = new TestEntity();
te.setName("sf solo!");
te.setAge(18);
te.setErrorCode("500");
te.setErrorMsg(e.getMessage());
return te;
}
}
上述代码中TestEntity为自定义返回实体
import lombok.Data;
@Data
public class TestEntity {
Integer age = 10;