spring Sping Boot @ExceptionHandler隐藏异常名称

h43kikqp  于 2022-11-21  发布在  Spring
关注(0)|答案(3)|浏览(184)

我使用的是Sping 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 字段?

oo7oh9g9

oo7oh9g91#

您可以在控制器建议中获取 * 错误属性 *,然后只保留 * 可公开字段 *。如下所示:

@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;
    }
}
i2loujxw

i2loujxw2#

对于那些使用 Spring Boot 2.x.
自2.0.0版起,ErrorAtturbutes的预设实作为DefaultErrorAttributes
DefaultErrorAttributes尽可能提供异常错误堆栈跟踪。通过设置以下项可以从响应中删除此字段:

server.error.include-stacktrace: never
zbdgwd5y

zbdgwd5y3#

我已经解决了这个bean风格的问题。在我的案例中,将下面的bean定义添加到REST层配置中,替换使用的ErrorAttributes,在没有任何异常处理运行时代码的情况下解决了这个问题。

@Bean
public ErrorAttributes errorAttributes() {
    return new DefaultErrorAttributes() {

        @Override
        public Map<String, Object> getErrorAttributes(
                RequestAttributes requestAttributes,
                boolean includeStackTrace) {

            Map<String, Object> errorAttributes
                = super.getErrorAttributes(requestAttributes, includeStackTrace);
            errorAttributes.remove("exception");
            return errorAttributes;
        }

    };
}

相关问题