You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swagger返回403错误但日志显示对象未找到的问题排查

问题解决步骤

1. 先修正异常对应的HTTP状态码

日志明确抛出了EntityNotFoundException但返回403,说明要么是全局异常处理器将该异常映射成了403,要么是Spring Security配置导致的拦截。先把异常绑定到正确的状态码:

两种实现方案:

方案一:给异常添加状态注解

自定义异常类继承EntityNotFoundException,标注对应的HTTP状态码:

@ResponseStatus(HttpStatus.NOT_FOUND) // 对应404状态码
public class SectionNotFoundException extends EntityNotFoundException {
    public SectionNotFoundException(String message) {
        super(message);
    }
}

之后在service层抛出这个自定义异常,Spring会自动返回404状态码。

方案二:配置全局异常处理器

编写全局异常处理类,专门处理EntityNotFoundException:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(EntityNotFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ExceptionDto handleSectionNotFound(EntityNotFoundException e) {
        return new ExceptionDto(e.getMessage());
    }

    // 其他异常的处理逻辑可在此扩展
}

这样抛出异常时,接口会返回404状态码和ExceptionDto结构的响应体。

2. 修正Swagger的文档配置

@ApiResponses仅用于生成接口文档,不会改变实际响应,因此需要将配置中的状态码修改为实际返回的404:

@ApiResponses(value = {
        @ApiResponse(responseCode = "200", description = "Раздел/подраздел успешно создан/обновлен"),
        @ApiResponse(responseCode = "401", description = "Требуется авторизация"),
        @ApiResponse(responseCode = "404", description = "Не найден объект", content = {@Content(schema = @Schema(implementation = ExceptionDto.class))}),
        @ApiResponse(responseCode = "500", description = "Внутренняя ошибка", content = {@Content(schema = @Schema(implementation = ExceptionDto.class))})
})

确保responseCode与实际接口返回的HTTP状态码完全匹配,Swagger测试时才会展示对应的错误描述和返回结构。

3. 排查Spring Security的403拦截问题

如果上述操作后仍返回403,检查Security配置:

  • 是否存在拦截规则误判请求权限的情况?
  • 是否开启了CSRF防护?Swagger发送POST请求时,若CSRF开启但未携带token,会返回403。测试阶段可临时关闭:
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.csrf().disable() // 生产环境按需开启
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .oauth2ResourceServer().jwt();
    }
}

4. 验证接口实际响应

不要直接用Swagger测试,先用Postman或curl调用接口,确认返回的状态码和响应体是否正确。如果直接调用返回404和ExceptionDto,说明Swagger只需配置正确即可正常展示;若仍返回403,继续排查Security或全局拦截器的逻辑。


内容的提问来源于stack exchange,提问作者Александра Дунаф

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 02:15:00