业务安全性检查要求隐藏500的敏感信息,并将错误变为400
import java.util.List; import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.springframework.boot.autoconfigure.web.ErrorProperties; import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController; import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver; import org.springframework.boot.web.servlet.error.ErrorAttributes; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping;
public class ErrorPageController extends BasicErrorController {
?? ?public ErrorPageController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, ?? ??? ??? ?List<ErrorViewResolver> errorViewResolvers) { ?? ??? ??? ? ?? ??? ?super(errorAttributes, errorProperties, errorViewResolvers);
?? ?}
?? ?@Override ?? ?protected Map<String, Object> getErrorAttributes(HttpServletRequest request, boolean includeStackTrace) { ?? ??? ? ?? ??? ?Map<String, Object> errorMap = super.getErrorAttributes(request, includeStackTrace); ?? ??? ?if(500==(int)errorMap.get("status")) { ?? ??? ??? ?errorMap.put("status", 400); ?? ??? ??? ?errorMap.remove("error"); ?? ??? ??? ?errorMap.remove("message"); ?? ??? ?} ?? ??? ?return errorMap; ?? ?} ?? ?@Override ?? ?@RequestMapping ?? ?public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) { ?? ??? ?Map<String, Object> body = getErrorAttributes(request, ?? ??? ??? ??? ?isIncludeStackTrace(request, MediaType.ALL)); ?? ??? ?HttpStatus status = getStatus(request); ?? ??? ?if(HttpStatus.INTERNAL_SERVER_ERROR.equals(status)) { ?? ??? ??? ?status=HttpStatus.BAD_REQUEST; ?? ??? ?} ?? ??? ?return new ResponseEntity<>(body, status); ?? ?}
?? ? ?? ?
}
文件二
?? ?@Bean ?? ?public ErrorPageController basicErrorController(ErrorAttributes errorAttributes,? ?? ??? ??? ?ServerProperties serverProperties,? ?? ??? ??? ?ObjectProvider<List<ErrorViewResolver>> errorViewResolversProvider) { ?? ??? ??? ? ?? ??? ?return new ErrorPageController(errorAttributes, serverProperties.getError(),? ?? ??? ??? ??? ?errorViewResolversProvider.getIfAvailable()); ?? ?}
|