springboot版本 2.1.1.RELEASE
ControllerAspect.java代码
@RestControllerAdvice
public class ControllerAspect {
@ExceptionHandler(Exception.class)
public Object dispose(final HttpServletRequest request, final HttpServletResponse response,
final Exception ex) {
Map<String,String> map = new HashMap<String,String>();
map.put("mgs", ex.getMessage());
map.put("code", "9999");
return map;
}
}
UserController代码:
@RestController
public class UserController {
@RequestMapping(value = "/test.json", method = { RequestMethod.POST,
RequestMethod.GET },produces = "application/json")
public Object refreshCache(final HttpServletRequest request, final String token) {
Map<String,String> map = new HashMap<String,String>();
map.put("mgs", "success");
map.put("code", "0000");
return map;
}
}
正常情况下:访问http://127.0.0.1:8080/test.json返回数据为格式是json
{"code":"0000","mgs":"success"}
在UserController里面抛出异常后
@RestController
public class UserController {
@RequestMapping(value = "/test.json", method = { RequestMethod.POST,
RequestMethod.GET },produces = "application/json")
public Object refreshCache(final HttpServletRequest request, final String token) {
Map<String,String> map = new HashMap<String,String>();
map.put("mgs", "success");
map.put("code", "0000");
System.out.println(1/0);
return map;
}
}
返回xml格式