If form invalid return error list in JSON response
436464
def form_invalid(self, form, prefix=None):
        
        response = super(FormAjaxMixin, self).form_invalid(form)
        if self.request.is_ajax():
            data = {
                "errors_list": self.add_prefix(form.errors, prefix),
            }
            return self.json_to_response(status=400, json_data=data,
                                         json_status=AjaxResponseStatus.ERROR)
        return response
691742
def errors(self,
               errors: List[str],
               code: Union[int, Tuple[int, str, str]] = HTTPStatus.BAD_REQUEST,
               key: str = 'errors',
               headers: Optional[Dict[str, str]] = None,
               ):
        
        return jsonify({key: errors}), code, headers or {}
117490
function(err) {

        var message = 'Error occured while performing a JSON-WSP request. ' +
            err.message + '\n' +
            JSON.stringify({
                options : curOpts
            }, null, '  ').yellow;

        logger.error(message);
    }
838996
protected void returnJsonSystemError(HttpServletRequest request, HttpServletResponse response,
            ResultCode resultCode) throws IOException {
        Map<String, Object> errors = new HashMap<String, Object>();
        errors.put(WebResponseConstant.MESSAGE_GLOBAL, resultCode.getMessage().getMessage());
        JsonObject<?> json = JsonObject.create();
        json.setStatus(resultCode.getCode());
        json.setStatusInfo(errors);
        response.setContentType("application/json; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.getWriter().write(JsonUtils.toJson(json));
    }
951577
def __invalid_request(self, error):
        
        # TODO: make this modifiable
        error = {
            'error': {
                'message': error
            }
        }
        abort(JsonResponse(status_code=400, data=error))
9139
def validate_json(data: str):
    
    result = None
    try:
        result = json.loads(data)
    except ValueError as error:
        log(ERROR, "invalid json: %s", error)

    return result
268212
def _check_for_errors(response, json_response):
        
        status_code = response.status_code
        try:
            response.raise_for_status()
        except requests.HTTPError as why:
            raise ApiError(str(why), reply_code=status_code)
        if isinstance(json_response, dict) and 'error' in json_response:
            raise ApiError(json_response['error'], reply_code=status_code)
1323460
def check_error(self, response, status, err_cd):
        " "

        if 'status' not in response:
            return False

        if response['status'] != status:
            return False

        if 'msgs' not in response:
            return False

        if not isinstance(response['msgs'], list):
            return False

        for msg in response['msgs']:

            if 'LVL' in msg and msg['LVL'] != 'ERROR':
                continue

            if 'ERR_CD' in msg and msg['ERR_CD'] == err_cd:
                return True

        return False
46875
private function getErrorResponse(FormInterface $form)
    {
        $errors = $form->getErrors();
        $errorCollection = [];

        foreach ($errors as $error) {
            $errorCollection[] = $error->getMessage();
        }

        return new JsonResponse([
            'messages' => $errorCollection,
        ], 400);
    }
1004322
def error(code, message, template):
    """"""
    if json_requested():
        return json_error(code, message)
    else:
        return render_template(template, message=message), code
335189
def _ValidateReturnValue(return_value, type_check_dict):
  """"""
  return_check = type_check_dict.get("returns", None)
  if not return_check:
    return []

  messages = []
  if not _ValidateValue(return_value, return_check):
    message = ("Invalid return value '%s'. Expected %s" %
               (return_value, _FormatTypeCheck(return_check)))
    messages.append(message)
  return messages
329323
def _is_valid_collection_json(self, json_repr):
        """"""
        collection = self._coerce_json_to_collection(json_repr)
        if collection is None:
            # invalid JSON, definitely broken
            return False
        aa = validate_collection(collection)
        errors = aa[0]
        for e in errors:
            _LOG.debug('> invalid JSON: {m}'.format(m=e.encode('utf-8')))
        if len(errors) > 0:
            return False
        return True
513988
private function handleApiError(
        $response_body,
        $response_code,
        $response_headers,
        $json_resp
    ) {

        switch ($response_code) {
            case 400:
                // format for the errors:
                // - [{"field":"amount","message":"Can refund at most GBP 0"}]
                // - [{"code":2,"text":"Invalid card details", "client": true, "merchant": false}]
                $message = "Bad (invalid) request";
                // @TODO - extract error parsing logic
                if ($json_resp && is_array($json_resp) && ! empty($json_resp)) {
                    if (isset($json_resp[0]['message'])) {
                        $message = $json_resp[0]['message'];
                    } else if (isset($json_resp[0]['text'])) {
                        $message = $json_resp[0]['text'];
                    }
                }
                throw new InvalidRequest($message,
                    $response_code, $response_body, $json_resp,
                    $response_headers);
            case 401:
                throw new Unauthorized("You need to provide credentials (an app's API key).",
                    $response_code,
                    $response_body, $json_resp,
                    $response_headers);
            case 403:
                throw new Forbidden("You are correctly authenticated but do not have access.",
                    $response_code, $response_body,
                    $json_resp,
                    $response_headers);
            case 404:
                throw new NotFound("Resource not found.",
                    $response_code, $response_body,
                    $json_resp,
                    $response_headers);
            case 409:
                throw new Conflict("Everything you submitted was fine at the time of validation, but something changed in the meantime and came into conflict with this (e.g. double-capture).",
                    $response_code, $response_body,
                    $json_resp,
                    $response_headers);
            default:
                throw new ApiException("Unknown api error",
                    $response_code,
                    $response_body,
                    $json_resp,
                    $response_headers);
        }
    }
507952
protected function buildFailedValidationResponse(Request $request, $errors)
    {
        $content = [
            'error'             => "The submitted data did not pass validation.",
            'validation_errors' => (array) $errors
        ];

        return ($request->ajax() && !$request->pjax() || $request->wantsJson())
            ? new JsonResponse($content, 422)
            : new Response($content, 422);
    }
1078035
function convertApiError(err) {
	if (err.error && err.error.response && err.error.response.text) {
		const obj = JSON.parse(err.error.response.text);
		if (obj.errors && obj.errors.length) {
			err = { message: obj.errors[0].message, error:err.error };
		}
	}
	return err;
}
740621
function _checkResult(type, err, obj, options)
{
    if (options) {
        if (options.logger) logger.logger(options.logger, 'parse:', type, options, lib.traceError(err), obj);
        if (options.datatype == "object" || options.datatype == "obj") return {};
        if (options.datatype == "list") return [];
        if (options.datatype == "str") return "";
    }
    return null;
}
490862
def check_response(self, resp):
        """"""
        if resp.status_code == 400:
            raise ApiException(json.loads(resp.content).get('message'))
        return resp