Send a 406 response for failed content negotiation
425271
protected function failTypeNegotiation()
    {
		$supported =  Request\TypeSupport::getSupport();
		$clientSupport =  Request\AcceptType::getContent();

		$supported = implode(',', $supported);
		$clientSupport = implode(',',$clientSupport);

		$this->withStatus(406)->withType(Response\ContentType::TEXT)
		->write("NOT SUPPORTED\nThis server does not support {$supported}.\nSupported formats: {$clientSupport}")
		->send();
		exit(1);
	}
302122
private void sendResponse(final HttpServletResponse res, final CmsSpellcheckingRequest request) throws IOException {

        final PrintWriter pw = res.getWriter();
        final JSONObject response = getJsonFormattedSpellcheckResult(request);
        pw.println(response.toString());
        pw.close();
    }
269176
function sendOptionsResponse(res, options, next) {
  try {
    var body = options.join(',');
    res.set('Allow', body);
    res.send(body);
  } catch (err) {
    next(err);
  }
}
964202
def format_response(status, body_object, headers={})
      if status == 204
        body = ''
      else
        body = case response_media_type
        when 'application/json'
          JSON.pretty_generate(body_object)
        when 'application/x-www-form-urlencoded'
          URI.encode_www_form(body_object)
        when 'application/xml'
          body_object.to_s
        when 'text/plain'
          body_object
        else
          # :nocov:
          raise NotImplementedError, "unsupported response media type #{response_media_type}"
          # :nocov:
        end
      end
      [status, headers.merge({'Content-Type' => response_media_type}), [body]]
    end
1022456
def send_response(self, body, set_content_type=True):
        
        settings = get_settings(self.application, force_instance=True)
        handler = settings[self.get_response_content_type()]
        content_type, data_bytes = handler.to_bytes(body)
        if set_content_type:
            self.set_header('Content-Type', content_type)
            self.add_header('Vary', 'Accept')
        self.write(data_bytes)
1079100
function sendResponse (err, resources) {
    // Extract the "data" of each Resource
    resources = _.map(resources, "data");

    // Use the current date/time as the "last-modified" header
    res.swagger.lastModified = new Date();

    // Set the response body (unless it's already been set by other middleware)
    if (err || res.body) {
      next(err);
    }
    else if (!res.swagger.isCollection) {
      // Response body is a single value, so only return the first item in the collection
      res.body = _.first(resources);
      next();
    }
    else {
      // Response body is the resource that was created/update/deleted
      res.body = resources;
      next();
    }
  }
724455
protected function sendResetLinkFailedResponse(Request $request, $response)
    {
        if ($request->expectsJson()) {
            return new JsonResponse([
                'message' =>  'The given data was invalid.',
                'errors' => [
                    'email' => trans($response)
                ]
            ], 422);
        }
        return back()->withErrors(
            ['email' => trans($response)]
        );
    }
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)
805367
def HttpResponse401(request, template=KEY_AUTH_401_TEMPLATE,
content=KEY_AUTH_401_CONTENT, content_type=KEY_AUTH_401_CONTENT_TYPE):
    
    return AccessFailedResponse(request, template, content, content_type, status=401)
311020
function rejectOnError(response, url) {
	const error = new Error(`${response.statusText} - status=${response.status}`);

	error.url = url;
	error.status = response.status;
	error.response = response.clone();

	debug( d => response.clone().text( text =>  d(`Response Error - url=${url}, text=${ text }`, response) ) );

	if (response.status === 422) {
		return response.json()
			.then( data => {
				error.validationErrors = data;

				throw error;
			})

		} else {
			return Store.reject(error);
		}
}
801357
function(oResponse) {
        // If response ID does not match last made request ID,
        // silently fail and wait for the next response
        if(oResponse && (this.connXhrMode == "ignoreStaleResponses") &&
                (oResponse.tId != oQueue.conn.tId)) {
            YAHOO.log("Ignored stale response", "warn", this.toString());
            return null;
        }
        // Error if no response
        else if(!oResponse) {
            this.fireEvent("dataErrorEvent", {request:oRequest, response:null,
                    callback:oCallback, caller:oCaller,
                    message:DS.ERROR_DATANULL});
            YAHOO.log(DS.ERROR_DATANULL, "error", this.toString());

            // Send error response back to the caller with the error flag on
            DS.issueCallback(oCallback,[oRequest, {error:true}], true, oCaller);

            return null;
        }
        // Forward to handler
        else {
            // Try to sniff data type if it has not been defined
            if(this.responseType === DS.TYPE_UNKNOWN) {
                var ctype = (oResponse.getResponseHeader) ? oResponse.getResponseHeader["Content-Type"] : null;
                if(ctype) {
                    // xml
                    if(ctype.indexOf("text/xml") > -1) {
                        this.responseType = DS.TYPE_XML;
                    }
                    else if(ctype.indexOf("application/json") > -1) { // json
                        this.responseType = DS.TYPE_JSON;
                    }
                    else if(ctype.indexOf("text/plain") > -1) { // text
                        this.responseType = DS.TYPE_TEXT;
                    }
                }
            }
            this.handleResponse(oRequest, oResponse, oCallback, oCaller, tId);
        }
    }
532782
function clientError(err, res) {
  log('error', err.message, { stack: err.stack });
  // They know it's a 400 already, we don't need to repeat the fact that its an error.
  const message = removePrefix(err.message, ':'),
    code = 400;

  sendDefaultResponseForCode(code, message, res);
}
649918
def recv(self):
        """"""
        try:
            items = self.poller.poll(self.timeout)
        except KeyboardInterrupt:
            return  # interrupted

        if items:
            # if we got a reply, process it
            msg = self.client.recv_multipart()
            self.close()
            if self.verbose:
                logging.info("I: received reply:")
                dump(msg)

            # Don't try to handle errors, just assert noisily
            assert len(msg) >= 4

            #first drop will be drop (cause empty)
            header = msg.pop(0)
            header = msg.pop(0)
            assert MDP.C_CLIENT == header

            #this one contains servicename
            #TODO: exploit this
            header = msg.pop(0)

            return msg
        else:
            logging.warn("W: permanent error, abandoning request")
972635
function (error, response, body) {
            if (error) {
                // Usually means we never got a response - server is down, no DNS entry, etc.
                _endDownload(downloadId, Errors.NO_SERVER_RESPONSE);
                return;
            }
            if (response.statusCode !== 200) {
                _endDownload(downloadId, [Errors.BAD_HTTP_STATUS, response.statusCode]);
                return;
            }

            var stream = temp.createWriteStream("brackets");
            if (!stream) {
                _endDownload(downloadId, Errors.CANNOT_WRITE_TEMP);
                return;
            }
            pendingDownloads[downloadId].localPath = stream.path;
            pendingDownloads[downloadId].outStream = stream;

            stream.write(body);
            _endDownload(downloadId);
        }
1250232
private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain; charset=UTF-8");
    ByteBuf content = Unpooled.copiedBuffer("Failure: " + status.toString() + "\r\n", CharsetUtil.UTF_8);

    ctx.write(response);
    // Close the connection as soon as the error message is sent.
    ctx.writeAndFlush(content).addListener(ChannelFutureListener.CLOSE);
  }
730689
function apiError(response, error) {
  var content = errorContentExt(ErrorType.server, error);
  send(response, content, StatusCode.internalServerError);
}
457613
static void sendFailedResponse(final ManagementRequestContext<RegistrationContext> context, final byte errorCode, final String message) throws IOException {
        final ManagementResponseHeader header = ManagementResponseHeader.create(context.getRequestHeader());
        final FlushableDataOutput output = context.writeMessage(header);
        try {
            // This is an error
            output.writeByte(DomainControllerProtocol.PARAM_ERROR);
            // send error code
            output.writeByte(errorCode);
            // error message
            if (message == null) {
                output.writeUTF("unknown error");
            } else {
                output.writeUTF(message);
            }
            // response end
            output.writeByte(ManagementProtocol.RESPONSE_END);
            output.close();
        } finally {
            StreamUtils.safeClose(output);
        }
    }