Spring Boot @ExceptionHandler 隐藏异常名称

2024-04-21

我正在使用 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表示?


您可以获得错误属性在你的控制器建议中,然后只保留暴露领域。类似于以下内容:

@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;
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Spring Boot @ExceptionHandler 隐藏异常名称 的相关文章

随机推荐