Parse a DAV error response

@param in response
@return a single error element or null
553563
public Element parseError(final InputStream in) {
    try {
      final Document doc = parseContent(in);

      final Element root = doc.getDocumentElement();

      expect(root, WebdavTags.error);

      final List<Element> els = getChildren(root);

      if (els.size() != 1) {
        return null;
      }

      return els.get(0);
    } catch (final Throwable ignored) {
      return null;
    }
  }
329677
def parse_reason(response, content):
    
    def first_error(data):
        errors = data['error']['errors']
        if len(errors) > 1:
            # we have more than one error. We should capture that?
            logging.info('Received {} errors'.format(len(errors)))
        return errors[0]

    try:
        json_data = json.loads(content)
        return first_error(json_data)['reason']
    except:
        return response.reason
715690
function extractError(resp) {
    var codes = {
      304: 'NotModified',
      403: 'Forbidden',
      400: 'BadRequest',
      404: 'NotFound'
    };

    var req = resp.request;
    var code = resp.httpResponse.statusCode;
    var body = resp.httpResponse.body || '';

    var headers = resp.httpResponse.headers || {};
    var region = headers['x-amz-bucket-region'] || null;
    var bucket = req.params.Bucket || null;
    var bucketRegionCache = req.service.bucketRegionCache;
    if (region && bucket && region !== bucketRegionCache[bucket]) {
      bucketRegionCache[bucket] = region;
    }

    var cachedRegion;
    if (codes[code] && body.length === 0) {
      if (bucket && !region) {
        cachedRegion = bucketRegionCache[bucket] || null;
        if (cachedRegion !== req.httpRequest.region) {
          region = cachedRegion;
        }
      }
      resp.error = AWS.util.error(new Error(), {
        code: codes[code],
        message: null,
        region: region
      });
    } else {
      var data = new AWS.XML.Parser().parse(body.toString());

      if (data.Region && !region) {
        region = data.Region;
        if (bucket && region !== bucketRegionCache[bucket]) {
          bucketRegionCache[bucket] = region;
        }
      } else if (bucket && !region && !data.Region) {
        cachedRegion = bucketRegionCache[bucket] || null;
        if (cachedRegion !== req.httpRequest.region) {
          region = cachedRegion;
        }
      }

      resp.error = AWS.util.error(new Error(), {
        code: data.Code || code,
        message: data.Message || null,
        region: region
      });
    }
    req.service.extractRequestIds(resp);
  }
490315
public void parse(CharSequence in, Appendable out) throws IOException, HttpErrorPage {
        ParserContextImpl ctx = new ParserContextImpl(out, httpRequest, httpResponse);
        Matcher matcher = pattern.matcher(in);
        int currentPosition = 0;
        while (matcher.find()) {
            String tag = matcher.group();
            ctx.characters(in, currentPosition, matcher.start());
            currentPosition = matcher.end();
            if (ctx.isCurrentTagEnd(tag)) {
                // check if this is the end tag for current element
                LOG.info("Processing end tag {}", tag);
                ctx.endElement(tag);
            } else {
                // if not, it is an opening tag for a new element
                LOG.info("Processing start tag {}", tag);
                ElementType type = null;
                for (ElementType t : elementTypes) {
                    if (t.isStartTag(tag)) {
                        type = t;
                        break;
                    }
                }
                Element element = type.newInstance();
                ctx.startElement(type, element, tag);
                if (type.isSelfClosing(tag)) {
                    ctx.endElement(tag);
                }

            }
        }
        // we reached the end of input
        ctx.characters(in, currentPosition, in.length());
    }
1107293
def parse
      response  = { errors: 0, status: 200, total_rows: 0, error_rows: []}
      index = 0
      batch = []

      begin
        CSV.foreach("#{@file_path}/#{@csv_file_name}", :encoding => 'iso-8859-1:UTF-8', headers: true) do |row|
          index += 1
          row_hash = row.to_hash
          response[:total_rows] += 1
          begin
            record, response[:errors], error_row = validate_record(response[:errors], row_hash, index)
            response[:error_rows] << error_row if error_row
              
            if @batch_process
              batch = add_to_batch(batch, record)
            else
              record.save!
            end
          rescue Exception => e
            response[:errors] +=1
            response[:error_rows] << log_and_return_error(row_hash, e, index)
          end
        end
        import_from_batch(batch)
      rescue Exception => e
        response[:errors] = 1
        response[:error_rows] = log_and_return_error({}, e, '')
        response[:status] = 500
      end

      if response[:error_rows].blank?
        post_parse_success_calls 
      elsif @error_file_needed
        error_in_upload(response[:error_rows])
      end

      response
    end
131004
private Object readResponse(Type returnType, JsonNode jsonNode, String id) throws Throwable {
		raiseExceptionIfNotValidResponseObject(jsonNode);
		final ObjectNode jsonObject = ObjectNode.class.cast(jsonNode);
		notifyAnswerListener(jsonObject);
		handleErrorResponse(jsonObject);
		if (hasResult(jsonObject)) {
			if (isReturnTypeInvalid(returnType)) {
				return null;
			}
			return constructResponseObject(returnType, jsonObject);
		}
		return null;
	}
412026
function parseResponse(response) {
    var code = response.statusCode;
    var type = code / 100 | 0;
    response.type = type;

    // basics
    switch (type) {
    case 1:
        response.info = type;
        break;
    case 2:
        response.ok = type;
        break;
    case 3:
        // ???
        break;
    case 4:
        response.clientError = type;
        response.error = type;
        response.ErrorClass = errors.HttpStatusError;
        break;
    case 5:
        response.serverError = type;
        response.error = type;
        response.ErrorClass = errors.HttpStatusError;
        break;
    }

    // error classes and sugar
    switch (code) {
    case 201:
        response.created = code;
        break;
    case 202:
        response.accepted = code;
        break;
    case 204:
        response.noContent = code;
        break;
    case 400:
        response.badRequest = code;
        break;
    case 401:
        response.unauthorized = code;
        response.ErrorClass = errors.AuthenticationRequiredError;
        break;
    case 403:
        response.forbidden = code;
        response.ErrorClass = errors.NotPermittedError;
        break;
    case 404:
        response.notFound = code;
        response.ErrorClass = errors.NotFoundError;
        break;
    case 406:
        response.notAcceptable = code;
        break;
    case 500:
        response.internalServerError = code;
        break;
    }

    // using body (and not status code)
    if (response.body && response.body.success === false) {
        if (!response.error) {
            response.error = 4; // assume is client error
            response.ErrorClass = errors.HttpStatusError;
        }
    }

    // null bodies
    if (_.includes([null, undefined, ""], response.body)) {
        if (!response.error) {
            response.error = 5; // assume the server fucked up
            response.ErrorClass = errors.HttpStatusError;
        }
    }

    return response;
}
87187
public byte[] readFrame( DataInputStream in ) {
		try {
			if( findMarker(in,SOI) && in.available() > 0 ) {
				return readJpegData(in, EOI);
			}
		} catch (IOException e) {}
		return null;
	}
570512
private static Response createErrorResponse(S3Exception e) {
    S3Error errorResponse = new S3Error(e.getResource(), e.getErrorCode());
    // Need to explicitly encode the string as XML because Jackson will not do it automatically.
    XmlMapper mapper = new XmlMapper();
    try {
      return Response.status(e.getErrorCode().getStatus())
          .entity(mapper.writeValueAsString(errorResponse)).build();
    } catch (JsonProcessingException e2) {
      return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
          .entity("Failed to encode XML: " + e2.getMessage()).build();
    }
  }
442512
def _get_error_response(self, exception):
        
        response_exceptions = {
            MimerDataException: HTTPBadRequestResponseException,
            NotAllowedException: HTTPForbiddenResponseException,
            UnsupportedMediaTypeException: HTTPUnsupportedMediaTypeResponseException,
            Http404: Http404,
            ResourceNotFoundException: Http404,
            NotAllowedMethodException: HTTPMethodNotAllowedResponseException,
            DuplicateEntryException: HTTPDuplicateResponseException,
            ConflictException: HTTPDuplicateResponseException,
        }
        response_exception = response_exceptions.get(type(exception))
        if response_exception:
            raise response_exception
        return super(RESTResourceMixin, self)._get_error_response(exception)
702645
@RequestMapping(produces = HttpHeaders.JSONAPI_CONTENT_TYPE)
	@ResponseBody
	public ResponseEntity<Document> errorToJsonApi(HttpServletRequest request) {
		Map<String, Object> body = getErrorAttributes(request,
				isIncludeStackTrace(request, MediaType.ALL));
		HttpStatus status = getStatus(request);

		ErrorDataBuilder errorDataBuilder = ErrorData.builder();
		for (Map.Entry<String, Object> attribute : body.entrySet()) {
			if (attribute.getKey().equals("status")) {
				errorDataBuilder.setStatus(attribute.getValue().toString());
			} else if (attribute.getKey().equals("error")) {
				errorDataBuilder.setTitle(attribute.getValue().toString());
			} else if (attribute.getKey().equals("message")) {
				errorDataBuilder.setDetail(attribute.getValue().toString());
			} else {
				errorDataBuilder.addMetaField(attribute.getKey(), attribute.getValue());
			}
		}
		Document document = new Document();
		document.setErrors(Arrays.asList(errorDataBuilder.build()));
		return new ResponseEntity<>(document, status);
	}
530751
private static JSONObject genError(HttpResponse response) throws JSONException {
    	String code		= response.getFirstHeader("X-Upwork-Error-Code").getValue();
    	String message	= response.getFirstHeader("X-Upwork-Error-Message").getValue();
    	
    	if (code == null) {
    		code = Integer.toString(response.getStatusLine().getStatusCode());
    	}
    	
    	if (message == null) {
    		message = response.getStatusLine().toString();
    	}

    	return new JSONObject("{error: {code: \"" + code + "\", message: \"" + message + "\"}}");
    }
120812
public static Document parseXMLResponse(String xmlStr) {
        if ((xmlStr == null) || (xmlStr.length() == 0)) {
            return null;
        }

        // FIXME: error handling for the DOM parsing...
        try {
            DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            return db.parse(new ByteArrayInputStream(xmlStr.getBytes()));
        } catch (ParserConfigurationException | IOException | SAXException pcex) {
            //ignore
        }

        return null;
    }
188305
public static HttpResponse parseMessage(InputStream in) throws IOException {
        HttpResponse m = new HttpResponse();
        m.parse(in);
        return m;
    }
1343457
function onEnd() {
		if ( err ) {
			err.message = body;
			return onError( err );
		}
		// debug( 'Response body: %s', body );

		body = parse( body );
		if ( body instanceof Error ) {
			err = {
				'status': 502,
				'message': 'unable to parse endpoint response data as JSON: ' + body.message
			};
			return onError( err );
		}
		clbk( null, body );
	}
910681
public static <T> T parse(Reader in, T toUpdate) {
		try {
			JSONParser p = new JSONParser(DEFAULT_PERMISSIVE_MODE);
			return p.parse(in, new UpdaterMapper<T>(defaultReader, toUpdate));
		} catch (Exception e) {
			return null;
		}
	}
723380
public static <T extends Errors> T parseError(ObjectMapper mapper, JsonNode errorResponse, Class<T> cls) throws JsonProcessingException {
        return mapper.treeToValue(errorResponse, cls);
    }