如何通过problem-spring-web自定义内部错误返回并隐藏错误详情?
使用Zalando problem-spring-web隐藏500错误详细信息的方法
要避免500内部服务器错误返回具体的异常栈或参数细节,统一返回友好提示,可通过以下两种方式实现:
方式一:自定义全局异常处理器
创建全局异常处理类,捕获所有未被处理的异常,返回自定义的Problem响应体:
import org.zalando.problem.Problem; import org.zalando.problem.Status; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.http.ResponseEntity; @ControllerAdvice public class GlobalErrorHandler { @ExceptionHandler(Throwable.class) public ResponseEntity<Problem> handleUncaughtExceptions(Throwable ex) { // 可在此添加日志记录,方便后端排查问题 // log.error("Internal server error occurred", ex); Problem errorResponse = Problem.builder() .withTitle("Internal Server Error") .withStatus(Status.INTERNAL_SERVER_ERROR) .withDetail("An unexpected error occurred.") .build(); return ResponseEntity.status(500).body(errorResponse); } }
这个类会拦截所有未被业务代码捕获的异常,返回统一的友好提示,同时可保留日志记录用于后端排查。
方式二:通过配置类统一修改响应格式
实现ProblemHandling接口,通过配置器统一指定500状态码的响应内容:
import org.zalando.problem.spring.web.advice.ProblemHandling; import org.zalando.problem.spring.web.advice.security.SecurityAdviceTrait; import org.springframework.context.annotation.Configuration; import org.zalando.problem.spring.web.advice.ExceptionHandlingConfigurer; import org.zalando.problem.Problem; import org.zalando.problem.Status; @Configuration public class CustomProblemConfig implements ProblemHandling, SecurityAdviceTrait { @Override public ExceptionHandlingConfigurer configure(ExceptionHandlingConfigurer configurer) { return configurer .withProblemDefaults(Status.INTERNAL_SERVER_ERROR, originalProblem -> Problem.builder() .withTitle(originalProblem.getTitle()) .withStatus(originalProblem.getStatus()) .withDetail("An unexpected error occurred.") .build() ); } }
这种方式通过配置类统一修改指定状态码的响应细节,无需单独编写每个异常的处理器,适合全局统一配置场景。
注意:若需对特定异常做单独处理,可优先在全局处理器中捕获这类异常,剩余未处理异常再触发500的统一响应。
内容的提问来源于stack exchange,提问作者Johannes Pertl
相关产品推荐
相关产品推荐

