spring 为什么ControllerAdvice中的POST不显示异常体

9lowa7mx  于 11个月前  发布在  Spring
关注(0)|答案(1)|浏览(87)

我有一个Spring的 Boot 应用程序与以下ControllerAdvice:

@ControllerAdvice
public class GlobalResponseStatusExceptionHandler {

    @ExceptionHandler(ResponseStatusException.class)
    public ResponseEntity<ResponseStatusExceptionModel> handleBadRequestException(ResponseStatusException ex, WebRequest h) {
        // if you want you can do some extra processing with message and status of an exception
        // or you can return it without any processing like this:

        String path = "";
        if (h instanceof ServletWebRequest) {
            ServletWebRequest servletWebRequest = (ServletWebRequest) h;
            path = servletWebRequest.getRequest().getRequestURI();
        }

        return new ResponseEntity<>(new ResponseStatusExceptionModel(
                ex.getStatusCode().value(),
                ex.getReason(),
                path
        ), ex.getStatusCode());
    }
}

字符串
我的ResponseStatusExceptionModel是:

public class ResponseStatusExceptionModel {

    // Example output
    // {"timestamp":"2023-12-15T23:25:11.778+00:00","status":403,"error":"Forbidden","message":"Access Denied","path":"/api/savedcontents"}
    private String timestamp;
    private int status;
    private String error;
    private String path;

    public String getTimestamp() {
        return timestamp;
    }

    public int getStatus() {
        return status;
    }

    public String getError() {
        return error;
    }

    public String getPath() {
        return path;
    }

    public ResponseStatusExceptionModel(int status, String error, String path) {
        this.timestamp = DateTimeFormatter.ISO_INSTANT.format(Instant.now().atZone(ZoneOffset.UTC)); // this is in iso8601
        this.status = status;
        this.error = error;
        this.path = path;
    }
}


我在我的securityConfiguration中也有以下内容:

request.requestMatchers("/error").permitAll();


在我的application.yml中,我有:

server:
  error:
    include-message: always
    include-binding-errors: always
    include-stacktrace: never


当我通过curl发出post请求时,我可以看到正文。但是当我通过浏览器发出请求时,我看不到错误消息(只有状态码)。为了显示错误,我需要设置什么?请注意,当我抛出'GET'请求时,我可以看到页面响应。

e4yzc0pl

e4yzc0pl1#

这是我个人使用的:

@RestControllerAdvice
public class ExceptionRestController {

    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ExceptionHandler(value = { FeignException.class })
    public ExceptionResponse handleFeignException(FeignException exception) {
        return new ExceptionResponse(exception);
    }

}

字符串
所以我想你错过了@ResponseBody

相关问题