我正在使用 Spring Boot 1.3.X 并具有以下内容:
@RestController
@RequestMapping(path = "/foo")
public class FooController {
@RequestMapping(method = RequestMethod.GET, params = { "fooBar" })
public Collection<Entry> firstFoo() {
//Do something
}
@RequestMapping(method = RequestMethod.GET, params = { "anotherFooBar" })
public Collection<Entry> secondFoo() {
//Do something other
}
}
按预期工作。传递错误的参数时,会引发以下异常:
{
"error": "Bad Request",
"exception": "org.springframework.web.bind.UnsatisfiedServletRequestParameterException",
"message": "Parameter conditions \"fooBar\" OR \"anotherFooBar\" not met for actual request parameters: elementalFormulae={C11}",
"path": "/foo",
"status": 400,
"timestamp": 1455287433961
}
然后我创建了一个 ExceptionHandler
,如下所示:
@ControllerAdvice
public class ExcptionController {
@ResponseStatus(value=HttpStatus.BAD_REQUEST, reason="Invalid parameter")
@ExceptionHandler(UnsatisfiedServletRequestParameterException.class)
private void foo() {
//Log exception
}
}
引发以下异常:
{
"error": "Bad Request",
"exception": "org.springframework.web.bind.UnsatisfiedServletRequestParameterException",
"message": "Invalid parameter",
"path": "/api/foo",
"status": 400,
"timestamp": 1455287904886
}
是否可以从 JSON
表示中排除 exception 字段?
最佳答案
您可以在 Controller 建议中获取错误属性,然后只保留可暴露字段。类似以下内容:
@ControllerAdvice
public class ExcptionController {
private static final List<String> EXPOSABLE_FIELDS = asList("timestamp", "status", "error", "message", "path");
@Autowired private ErrorAttributes errorAttributes;
@ExceptionHandler(UnsatisfiedServletRequestParameterException.class)
private ResponseEntity foo(HttpServletRequest request) {
Map<String, Object> errors = getErrorAttributes(request);
errors.put("message", "Invalid parameter");
return ResponseEntity.badRequest().body(errors);
}
private Map<String, Object> getErrorAttributes(HttpServletRequest request) {
ServletRequestAttributes requestAttributes = new ServletRequestAttributes(request);
final boolean WITHOUT_STACK_TRACE = false;
Map<String, Object> attributes = errorAttributes.getErrorAttributes(requestAttributes, WITHOUT_STACK_TRACE);
// log exception before removing it
attributes.keySet().removeIf(key -> !EXPOSABLE_FIELDS.contains(key));
return attributes;
}
}
关于java - Spring Boot @ExceptionHandler 隐藏异常名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35365266/