如何移除Spring Boot中ResponseStatusException返回JSON里的path字段
移除Spring Boot REST错误JSON中的path参数
要移除Spring Boot默认错误响应里的path字段,下面是两种实用方案:
方案一:自定义ErrorAttributes(推荐)
Spring Boot默认通过DefaultErrorAttributes生成错误响应属性,我们可以继承这个类并移除path字段:
import org.springframework.boot.web.error.ErrorAttributeOptions; import org.springframework.boot.web.servlet.error.DefaultErrorAttributes; import org.springframework.stereotype.Component; import org.springframework.web.context.request.WebRequest; import java.util.Map; @Component public class CustomErrorAttributes extends DefaultErrorAttributes { @Override public Map<String, Object> getErrorAttributes(WebRequest webRequest, ErrorAttributeOptions options) { // 获取默认的错误属性集合 Map<String, Object> errorAttributes = super.getErrorAttributes(webRequest, options); // 移除path字段 errorAttributes.remove("path"); return errorAttributes; } }
把这个类放到Spring能扫描到的包下,它会自动替换默认的DefaultErrorAttributes,之后返回的错误JSON就不会包含path了。
方案二:全局异常处理自定义响应体
如果项目用@ControllerAdvice做全局异常处理,可以直接构建不含path的响应体:
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import java.time.LocalDateTime; import java.util.HashMap; import java.util.Map; @ControllerAdvice public class GlobalExceptionHandler { // 处理所有异常的通用方法 @ExceptionHandler(Exception.class) public ResponseEntity<Object> handleAllExceptions(Exception ex) { Map<String, Object> errorBody = new HashMap<>(); errorBody.put("timestamp", LocalDateTime.now().toString()); errorBody.put("status", HttpStatus.NOT_FOUND.value()); errorBody.put("error", HttpStatus.NOT_FOUND.getReasonPhrase()); errorBody.put("message", ex.getMessage()); // 不添加path字段 return new ResponseEntity<>(errorBody, HttpStatus.NOT_FOUND); } // 针对自定义异常的处理(比如员工不存在的情况) @ExceptionHandler(EmployeeNotFoundException.class) public ResponseEntity<Object> handleEmployeeNotFound(EmployeeNotFoundException ex) { Map<String, Object> errorBody = new HashMap<>(); errorBody.put("timestamp", LocalDateTime.now().toString()); errorBody.put("status", HttpStatus.NOT_FOUND.value()); errorBody.put("error", "Not Found"); errorBody.put("message", "Employee Not Found :" + ex.getEmpId()); return new ResponseEntity<>(errorBody, HttpStatus.NOT_FOUND); } }
这种方式完全掌控响应内容,按需添加字段,自然不会出现path。
内容的提问来源于stack exchange,提问作者Akshay Bhimanpalli
相关产品推荐
相关产品推荐

