As a complementary, for those who might meet the same issue as mine, I’m using $.ajax
to post form data to server and I also got the 400
error at first.
Assume I have a javascript variable,
var formData = {
"name":"Gearon",
"hobby":"Be different"
};
Do not use variable formData
directly as the value of key data
like below:
$.ajax({
type: "post",
dataType: "json",
url: "http://localhost/user/add",
contentType: "application/json",
data: formData,
success: function(data, textStatus){
alert("Data: " + data + "nStatus: " + status);
}
});
Instead, use JSON.stringify to encapsulate the formData
as below:
$.ajax({
type: "post",
dataType: "json",
url: "http://localhost/user/add",
contentType: "application/json",
data: JSON.stringify(formData),
success: function(data, textStatus){
alert("Data: " + data + "nStatus: " + status);
}
});
Anyway, as others have illustrated, the error is because the server could not recognize the request cause malformed syntax, I’m just raising a instance at practice. Hope it would be helpful to someone.
Stay organized with collections
Save and categorize content based on your preferences.
The following document provides reference information about the status codes
and error messages that are used in the Cloud Storage JSON API. For
the page specific to the Cloud Storage XML API, see
HTTP status and error codes for XML.
Error Response Format
Cloud Storage uses the standard HTTP error reporting format for the
JSON API. Successful requests return HTTP status codes in the 2xx range. Failed
requests return status codes in the 4xx and 5xx ranges. Requests that require a
redirect returns status codes in the 3xx range. Error responses usually include
a JSON document in the response body, which contains information about the
error.
The following examples show some common errors. Note that the header
information in the responses is omitted.
The following is an example of an error response you receive if you try to
list the buckets for a project but do not provide an authorization header.
401 Unauthorized { "error": { "errors": [ { "domain": "global", "reason": "required", "message": "Login Required", "locationType": "header", "location": "Authorization" } ], "code": 401, "message": "Login Required" } }
403 Forbidden
This is an example of an error response you receive if you try to list the
buckets of a non-existent project or one in which you don’t have permission
to list buckets.
403 Forbidden { "error": { "errors": [ { "domain": "global", "reason": "forbidden", "message": "Forbidden" } ], "code": 403, "message": "Forbidden" } }
404 Not Found
The following is an example of an error response you receive if you try to
retrieve an object that does not exist.
404 Not Found { "error": { "errors": [ { "domain": "global", "reason": "notFound", "message": "Not Found" } ], "code": 404, "message": "Not Found" } }
409 Conflict
The following is an example of an error response you receive if you try to
create a bucket using the name of a bucket you already own.
409 Conflict { "error": { "errors": [ { "domain": "global", "reason": "conflict", "message": "You already own this bucket. Please select another name." } ], "code": 409, "message": "You already own this bucket. Please select another name." } }
The following table describes the elements that can appear in the response body
of an error. Fields should be used together to help determine the problem.
Also, the example values given below are meant for illustration and are not an
exhaustive list of all possible values.
Element | Description |
---|---|
code |
An HTTP status code value, without the textual description.
Example values include: |
error |
A container for the error information. |
errors |
A container for the error details. |
errors.domain |
The scope of the error. Example values include: global and push . |
errors.location |
The specific item within the locationType that caused the error. For example, if you specify an invalid value for a parameter, the location will be the name of the parameter.
Example values include: |
errors.locationType |
The location or part of the request that caused the error. Use with location to pinpoint the error. For example, if you specify an invalid value for a parameter, the locationType will be parameter and the location will be the name of the parameter.
Example values include |
errors.message |
Description of the error.
Example values include |
errors.reason |
Example values include invalid , invalidParameter , and required . |
message |
Description of the error. Same as errors.message . |
HTTP Status and Error Codes
This section provides a non-exhaustive list of HTTP status and error codes that
the Cloud Storage JSON API uses. The 1xx
Informational and 2xx
Success codes are not discussed here. For more information, see Response Status
Codes in RFC 7231 §6, RFC 7232 §4,
RFC 7233 §4, RFC 7235 §3, and RFC 6585.
302—Found
Reason | Description |
---|---|
found | Resource temporarily located elsewhere according to the Location header. |
303—See Other
Reason | Description |
---|---|
mediaDownloadRedirect | When requesting a download using alt=media URL parameter, the direct URL path to use is prefixed by /download . If this is omitted, the service will issue this redirect with the appropriate media download path in the Location header. |
304—Not Modified
Reason | Description |
---|---|
notModified | The conditional request would have been successful, but the condition was false, so no body was sent. |
307—Temporary Redirect
Reason | Description |
---|---|
temporaryRedirect | Resource temporarily located elsewhere according to the Location header. Among other reasons, this can occur when cookie-based authentication is being used, e.g., when using the Storage Browser, and it receives a request to download content. |
308—Resume Incomplete
Description |
---|
Indicates an incomplete resumable upload and provides the range of bytes already received by Cloud Storage. Responses with this status do not contain a body. |
400—Bad Request
[Domain.]Reason | Description |
---|---|
badRequest | The request cannot be completed based on your current Cloud Storage settings. For example, you cannot lock a retention policy if the requested bucket doesn’t have a retention policy, and you cannot set ACLs if the requested bucket has uniform bucket-level access enabled. |
badRequestException | The retention period on a locked bucket cannot be reduced. |
cloudKmsBadKey | Bad Cloud KMS key. |
cloudKmsCannotChangeKeyName | Cloud KMS key name cannot be changed. |
cloudKmsDecryptionKeyNotFound | Resource’s Cloud KMS decryption key not found. |
cloudKmsDisabledKey | Cloud KMS key is disabled, destroyed, or scheduled to be destroyed. |
cloudKmsEncryptionKeyNotFound | Cloud KMS encryption key not found. |
cloudKmsKeyLocationNotAllowed | Cloud KMS key location not allowed. |
corsRequestWithXOrigin | CORS request contains an XD3 X-Origin header. |
customerEncryptionAlgorithmIsInvalid | Missing an encryption algorithm, or the provided algorithm is not «AE256.» |
customerEncryptionKeyFormatIsInvalid | Missing an encryption key, or it is not Base64 encoded, or it does not meet the required length of the encryption algorithm. |
customerEncryptionKeyIsIncorrect | The provided encryption key is incorrect. |
customerEncryptionKeySha256IsInvalid | Missing a SHA256 hash of the encryption key, or it is not Base64 encoded, or it does not match the encryption key. |
invalidAltValue | The value for the alt URL parameter was not recognized. |
invalidArgument | The value for one of fields in the request body was invalid. |
invalidParameter | The value for one of the URL parameters was invalid. In addition to normal URL parameter validation, any URL parameters that have a corresponding value in provided JSON request bodies must match if they are both specified. If using JSONP, you will get this error if you provide an alt parameter that is not json . |
notDownload | Uploads or normal API request was sent to a /download/* path. Use the same path, but without the /download prefix. |
notUpload | Downloads or normal API request was sent to a /upload/* path. Use the same path, but without the /upload prefix. |
parseError | Could not parse the body of the request according to the provided Content-Type. |
push.channelIdInvalid | Channel id must match the following regular expression: [A-Za-z0-9\-_\+/=]+ |
push.channelIdNotUnique | storage.objects.watchAll ‘s id property must be unique across channels. |
push.webhookUrlNoHostOrAddress | storage.objects.watchAll ‘s address property must contain a valid URL. |
push.webhookUrlNotHttps | storage.objects.watchAll ‘s address property must be an HTTPS URL. |
required | A required URL parameter or required request body JSON property is missing. |
resourceIsEncryptedWithCustomerEncryptionKey | The resource is encrypted with a customer-supplied encryption key, but the request did not provide one. |
resourceNotEncryptedWithCustomerEncryptionKey | The resource is not encrypted with a customer-supplied encryption key, but the request provided one. |
turnedDown | A request was made to an API version that has been turned down. Clients will need to update to a supported version. |
userProjectInvalid | The user project specified in the request is invalid, either because it is a malformed project id or because it refers to a non-existent project. |
userProjectMissing | The requested bucket has Requester Pays enabled, the requester is not an owner of the bucket, and no user project was present in the request. |
wrongUrlForUpload | storage.objects.insert must be invoked as an upload rather than a metadata. |
401—Unauthorized
[Domain.]Reason | Description |
---|---|
AuthenticationRequiredRequesterPays | Access to a Requester Pays bucket requires authentication. |
authError | This error indicates a problem with the authorization provided in the request to Cloud Storage. The following are some situations where that will occur:
|
lockedDomainExpired | When downloading content from a cookie-authenticated site, e.g., using the Storage Browser, the response will redirect to a temporary domain. This error will occur if access to said domain occurs after the domain expires. Issue the original request again, and receive a new redirect. |
required | Access to a non-public method that requires authorization was made, but none was provided in the Authorization header or through other means. |
403—Forbidden
[Domain.]Reason | Description |
---|---|
accountDisabled | The account associated with the project that owns the bucket or object has been disabled. Check the Google Cloud console to see if there is a problem with billing, and if not, contact account support. |
countryBlocked | The Cloud Storage JSON API is restricted by law from operating with certain countries. |
forbidden | According to access control policy, the current user does not have access to perform the requested action. This code applies even if the resource being acted on doesn’t exist. |
insufficientPermissions | According to access control policy, the current user does not have access to perform the requested action. This code applies even if the resource being acted on doesn’t exist. |
objectUnderActiveHold | Object replacement or deletion is not allowed due to an active hold on the object. |
retentionPolicyNotMet | Object replacement or deletion is not allowed until the object meets the retention period set by the retention policy on the bucket. |
sslRequired | Requests to this API require SSL. |
stopChannelCallerNotOwner | Calls to storage.channels.stop require that the caller own the channel. |
UserProjectAccessDenied | The requester is not authorized to use the project specified in the userProject portion of the request. The requester must have the serviceusage.services.use permission for the specified project. |
UserProjectAccountProblem | There is a problem with the project used in the request that prevents the operation from completing successfully. One issue could be billing. Check the billing page to see if you have a past due balance or if the credit card (or other payment mechanism) on your account is expired. For project creation, see the Projects page in the Google Cloud console. For other problems, see the Resources and Support page. |
404—Not Found
Reason | Description |
---|---|
notFound | Either there is no API method associated with the URL path of the request, or the request refers to one or more resources that were not found. |
405—Method Not Allowed
Reason | Description |
---|---|
methodNotAllowed | The HTTP verb is not supported by the URL endpoint used in the request. This can happen, for example, when using the wrong verb with the /upload or /download URLs. |
408—Request Timeout
Reason | Description |
---|---|
uploadBrokenConnection | The request timed out. You should retry the request using truncated exponential backoff. |
409—Conflict
Reason | Description |
---|---|
conflict | A request to change a resource, usually a storage.*.update or storage.*.patch method, failed to commit the change due to a conflicting concurrent change to the same resource. The request can be retried, though care should be taken to consider the new state of the resource to avoid blind replacement of another agent’s changes. |
410—Gone
Description |
---|
You have attempted to use a resumable upload session or rewrite token that is no longer available. If the reported status code was not successful and you still wish to complete the upload or rewrite, you must start a new session. |
411—Length Required
Description |
---|
You must provide the Content-Length HTTP header. This error has no response body. |
412—Precondition Failed
Reason | Description |
---|---|
conditionNotMet | At least one of the pre-conditions you specified did not hold. |
orgPolicyConstraintFailed | Request violates an OrgPolicy constraint. |
413—Payload Too Large
Reason | Description |
---|---|
uploadTooLarge | This error arises if you:
|
416—Requested Range Not Satisfiable
Reason | Description |
---|---|
requestedRangeNotSatisfiable | The requested Range cannot be satisfied. |
429—Too Many Requests
[Domain.]Reason | Description |
---|---|
usageLimits.rateLimitExceeded | A Cloud Storage JSON API usage limit was exceeded. If your application tries to use more than its limit, additional requests will fail. Throttle your client’s requests, and/or retry requests using truncated exponential backoff. |
499—Client Closed Request
Description |
---|
The resumable upload was cancelled at the client’s request prior to completion. This error has no response body. |
500—Internal Server Error
Reason | Description |
---|---|
backendError | We encountered an internal error. You should retry the request using truncated exponential backoff. |
internalError | We encountered an internal error. You should retry the request using truncated exponential backoff. |
502—Bad Gateway
This error is generated when there was difficulty reaching an internal service.
It is not formatted with a JSON document. You should retry the request
using truncated exponential backoff.
503—Service Unavailable
Reason | Description |
---|---|
backendError | We encountered an internal error. You should retry the request using truncated exponential backoff. |
504—Gateway Timeout
This error is generated when there was difficulty reaching an internal service.
It is not formatted with a JSON document. You should retry the request
using truncated exponential backoff.
Except as otherwise noted, the content of this page is licensed under the Creative Commons Attribution 4.0 License, and code samples are licensed under the Apache 2.0 License. For details, see the Google Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.
Last updated 2023-05-26 UTC.
Когда я только начинал работать с Express и пытался разобраться с тем, как обрабатывать ошибки, мне пришлось нелегко. Возникало такое ощущение, будто никто не писал о том, что мне было нужно. В итоге мне пришлось самому искать ответы на мои вопросы. Сегодня я хочу рассказать всё, что знаю об обработке ошибок в Express-приложениях. Начнём с синхронных ошибок.
Обработка синхронных ошибок
Если вам нужно обработать синхронную ошибку, то вы можете, для начала, с помощью инструкции throw
, выдать такую ошибку в обработчике запроса Express. Обратите внимание на то, что обработчики запросов ещё называют «контроллерами», но я предпочитаю использовать термин «обработчик запросов» так как он кажется мне понятнее.
Вот как это выглядит:
app.post('/testing', (req, res) => {
throw new Error('Something broke! ')
})
Такие ошибки можно перехватить с помощью обработчика ошибок Express. Если вы не написали собственный обработчик ошибок (подробнее об этом мы поговорим ниже), то Express обработает ошибку с помощью обработчика, используемого по умолчанию.
Вот что делает стандартный обработчик ошибок Express:
- Устанавливает код состояния HTTP-ответа в значение 500.
- Отправляет сущности, выполнившей запрос, текстовый ответ.
- Логирует текстовый ответ в консоль.
Сообщение об ошибке, выведенное в консоль
Обработка асинхронных ошибок
Для обработки асинхронных ошибок нужно отправить ошибку обработчику ошибок Express через аргумент next
:
app.post('/testing', async (req, res, next) => {
return next(new Error('Something broke again! '))
})
Вот что попадёт в консоль при логировании этой ошибки.
Сообщение об ошибке, выведенное в консоль
Если вы пользуетесь в Express-приложении конструкцией async/await, то вам понадобится использовать функцию-обёртку, наподобие express-async-handler. Это позволяет писать асинхронный код без блоков try/catch. Подробнее об async/await в Express можно почитать здесь.
const asyncHandler = require('express-async-handler')
app.post('/testing', asyncHandler(async (req, res, next) => {
// Сделать что-нибудь
}))
После того, как обработчик запроса обёрнут в express-async-handler
, то можно, так же, как было описано выше, выбросить ошибку с использованием инструкции throw
. Эта ошибка попадёт к обработчику ошибок Express.
app.post('/testing', asyncHandler(async (req, res, next) => {
throw new Error('Something broke yet again! ')
}))
Сообщение об ошибке, выведенное в консоль
Написание собственного обработчика ошибок
Обработчики ошибок Express принимают 4 аргумента:
- error
- req
- res
- next
Размещать их нужно после промежуточных обработчиков и маршрутов.
app.use(/*...*/)
app.get(/*...*/)
app.post(/*...*/)
app.put(/*...*/)
app.delete(/*...*/)
// Собственный обработчик ошибок нужно поместить после всех остальных промежуточных обработчиков
app.use((error, req, res, next) => { /* ... */ })
Если создать собственный обработчик ошибок, то Express прекратит использование стандартного обработчика. Для того чтобы обработать ошибку, нужно сформировать ответ для фронтенд-приложения, которое обратилось к конечной точке, в которой возникла ошибка. Это означает, что нужно выполнить следующие действия:
- Сформировать и отправить подходящий код состояния ответа.
- Сформировать и отправить подходящий ответ.
То, какой именно код состояния подойдёт в каждом конкретном случае, зависит от того, что именно произошло. Вот список типичных ошибок, к обработке которых вы должны быть готовы:
- Ошибка
400 Bad Request
. Используется в двух ситуациях. Во-первых — тогда, когда пользователь не включил в запрос необходимое поле (например — в отправленной платёжной форме не заполнено поле со сведениями о кредитной карте). Во-вторых — тогда, когда в запросе содержатся некорректные данные (например — ввод в поле пароля и в поле подтверждения пароля разных паролей). - Ошибка
401 Unauthorized
. Этот код состояния ответа применяется в том случае, если пользователь ввёл неправильные учётные данные (вроде имени пользователя, адреса электронной почты или пароля). - Ошибка
403 Forbidden
. Используется в тех случаях, когда пользователю не разрешён доступ к конечной точке. - Ошибка
404 Not Found
. Применяется в тех случаях, когда конечную точку невозможно обнаружить. - Ошибка
500 Internal Server Error
. Применяется тогда, когда запрос, отправленный фронтендом, сформирован правильно, но на бэкенде при этом возникла какая-то ошибка.
После того, как определён подходящий код состояния ответа, его нужно установить с помощью res.status
:
app.use((error, req, res, next) => {
// Ошибка, выдаваемая в ответ на неправильно сформированный запрос
res.status(400)
res.json(/* ... */)
})
Код состояния ответа должен соответствовать сообщению об ошибке. Для этого нужно отправлять код состояния вместе с ошибкой.
Легче всего это сделать с помощью пакета http-errors. Он позволяет отправлять в ошибке три фрагмента информации:
- Код состояния ответа.
- Сообщение, сопутствующее ошибке.
- Любые данные, которые нужно отправить (это необязательно).
Вот как установить пакет http-errors
:
npm install http-errors --save
Вот как этим пакетом пользоваться:
const createError = require('http-errors')
// Создание ошибки
throw createError(status, message, properties)
Рассмотрим пример, который позволит как следует в этом всём разобраться.
Представим, что мы пытаемся обнаружить пользователя по адресу его электронной почты. Но этого пользователя найти не удаётся. В результате мы решаем отправить в ответ на соответствующий запрос ошибку User not found
, сообщающую вызывающей стороне о том, что пользователь не найден.
Вот что нам нужно будет сделать при создании ошибки:
- Установить код состояния ответа как
400 Bad Request
(ведь пользователь ввёл неправильные данные). Это будет наш первый параметр. - Отправить вызывающей стороне сообщение наподобие
User not found
. Это будет второй параметр.
app.put('/testing', asyncHandler(async (req, res) => {
const { email } = req.body
const user = await User.findOne({ email })
// Если пользователь не найден - выбросим ошибку
if (!user) throw createError(400, `User '${email}' not found`)
}))
Получить код состояния можно с помощью конструкции error.status
, а сообщение ошибки — с помощью error.message
:
// Логирование ошибки
app.use((error, req, res, next) => {
console.log('Error status: ', error.status)
console.log('Message: ', error.message)
})
Результат логирования ошибки в консоли
Затем состояние ответа устанавливают с помощью res.status
, а сообщение записывают в res.json
:
app.use((error, req, res, next) => {
// Установка кода состояния ответа
res.status(error.status)
// Отправка ответа
res.json({ message: error.message })
})
Лично я предпочитаю отправлять в подобных ответах код состояния, сообщение и результат трассировки стека. Это облегчает отладку.
app.use((error, req, res, next) => {
// Установка кода состояния ответа
res.status(error.status)
// Отправка ответа
res.json({
status: error.status,
message: error.message,
stack: error.stack
})
})
▍Код состояния ответа, используемый по умолчанию
Если источником ошибки не является createError
, то у неё не будет свойства status
. Вот пример, в котором сделана попытка прочесть несуществующий файл с помощью fs.readFile
:
const fs = require('fs')
const util = require('util')
// Преобразуем readFile из функции, использующей коллбэки, в async/await-функцию.
// Подробности об этом смотрите здесь: https://zellwk.com/blog/callbacks-to-promises
const readFilePromise = util.promisify(fs.readFile)
app.get('/testing', asyncHandler(async (req, res, next) => {
const data = await readFilePromise('some-file')
})
У такого объекта ошибки не будет свойства status
:
app.use((error, req, res, next) => {
console.log('Error status: ', error.status)
console.log('Message: ', error.message)
})
Результат логирования ошибки в консоли
В подобных случаях можно задать код ошибки, используемый по умолчанию. А именно, речь идёт об ошибке 500 Internal Server Error
:
app.use((error, req, res, next) => {
res.status(error.status || 500)
res.json({
status: error.status,
message: error.message,
stack: error.stack
})
})
▍Изменение кода состояния ошибки
Предположим, мы собираемся прочитать некий файл, воспользовавшись данными, предоставленными пользователем. Если такого файла не существует, это значит, что нам нужно выдать ошибку 400 Bad Request
. Ведь в том, что файл найти не удаётся, нет вины сервера.
В подобном случае нужно воспользоваться конструкцией try/catch для перехвата исходной ошибки. Затем нужно воссоздать объект ошибки с помощью createError
:
app.get('/testing', asyncHandler(async (req, res, next) => {
try {
const { file } = req.body
const contents = await readFilePromise(path.join(__dirname, file))
} catch (error) {
throw createError(400, `File ${file} does not exist`)
}
})
▍Обработка ошибок 404
Если запрос прошёл через все промежуточные обработчики и маршруты, но так и не был обработан, это означает, что конечная точка, соответствующая такому запросу, не была найдена.
Для обработки ошибок 404 Not Found
нужно добавить, между маршрутами и обработчиком ошибок, дополнительный обработчик. Вот как выглядит создание объекта ошибки 404:
// Промежуточные обработчики...
// Маршруты...
app.use((req, res, next) => {
next(createError(404))
})
// Обработчик ошибок...
Сведения об ошибке
▍Замечания об ошибке ERR_HTTP_HEADERS_SENT
Не впадайте в панику если видите сообщение об ошибке ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client
. Она возникает из-за того, что в одном и том же обработчике многократно вызывается метод, устанавливающий заголовки ответа. Вот методы, вызов которых приводит к автоматической установке заголовков ответа:
- res.send
- res.json
- res.render
- res.sendFile
- res.sendStatus
- res.end
- res.redirect
Так, например, если вы вызовете методы res.render
и res.json
в одном и том же обработчике ответа, то вы получите ошибку ERR_HTTP_HEADERS_SENT
:
app.get('/testing', (req, res) => {
res.render('new-page')
res.json({ message: '¯_(ツ)_/¯' })
})
В результате, в том случае, если вы сталкиваетесь с этой ошибкой, тщательно проверьте код обработчиков ответа и убедитесь в том, что в нём нет ситуаций, в которых вызывается несколько вышеописанных методов.
▍Обработка ошибок и потоковая передача данных
Если что-то идёт не так при потоковой передаче ответа фронтенду, то можно столкнуться с той же самой ошибкой ERR_HTTP_HEADERS_SENT
.
В подобном случае обработку ошибок нужно передать стандартным обработчикам. Такой обработчик отправит ошибку и автоматически закроет соединение.
app.use((error, req, res, next) => {
// Сделать это нужно только в том случае, если ответ передаётся в потоковом режиме
if (res.headersSent) {
return next(error)
}
// Остальной код обработки ошибок
})
Итоги
Сегодня я рассказал вам всё, что знаю об обработке ошибок в Express. Надеюсь, это поможет вам писать более надёжные Express-приложения.
Уважаемые читатели! Как вы обрабатываете ошибки в своих Node.js-проектах?
Answer by Hendrix Morris
The HyperText Transfer Protocol (HTTP) 400 Bad Request response status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).,HTTP response status codes,Warning: The client should not repeat this request without modification.,
HTTP guide
Basics of HTTP
Overview of HTTP
Evolution of HTTP
HTTP Messages
A typical HTTP session
Connection management in HTTP/1.x
Protocol upgrade mechanism
400 Bad Request
Answer by Averi Duncan
Also, enclose your data as JSON in the request body, don’t pass them as URL parameters. You are passing JSON data in your curl example as well.,and corresponding curl request is ,Please be sure to answer the question. Provide details and share your research!,Making statements based on opinion; back them up with references or personal experience.
Also, enclose your data as JSON
in the request body, don’t pass them as URL parameters. You are passing JSON
data in your curl
example as well.
import requests
data = {
"externalId": "801411",
"name": "RD Core",
"description": "Tenant create",
"subscriptionType": "MINIMAL",
"features": {
"capture": False,
"correspondence": True,
"vault": False
}
}
response = requests.post(
url="http://localhost:9100/tenants/",
json=data
)
print response.status_code, response.reason
Answer by Melani Patrick
The 400 (Bad Request) status code indicates that the server cannot or will not process the request due to something that is perceived to be a client error (e.g., malformed request syntax, invalid request message framing, or deceptive request routing).,The key concept to understand here is that the 400 Bad Request error is something that has to do with the submitted request from the client before it is even processed by the server.,The 400 Bad Request Error is an HTTP response status code
that indicates the server was unable to process (understand) the request sent by the client due to incorrect syntax, invalid request message framing, or deceptive request routing.,The 4xx family of status codes is the one we’re investigating here as they relate to invalid or corrupt requests from the client. Specifically, we’ll take a closer look at the 400 Bad Request error: what this error means, what causes it as well as some specific steps to fix the issue.
This is surprisingly easy to do by mistake and can happen if a URL has been encoding incorrectly. The following link is an example of a URL containing characters the server won’t be able to process, hence a 400 Bad Request error is triggered.
https://twitter.com/share?lang=en&text=Example%20of%20malformed%%20characters%20in%20URL
https://twitter.com/share?lang=en&text=Example%20of%20malformed%%20characters%20in%20URL
Answer by Dexter English
I received this error and got this error message: The content value must be a string at least one character in length.,Recommend double-checking to make sure your code is not violating any of those requirements and, if not, filing a support ticket to further debug the request.,I am having the same error using flask-sendgrid. I have the latest version of sendgrid installed. When launching my flask server, I can send one email fine then when I request to send another one it fails.,Thanks @linehammer, I figured that out ? As I stated in my other issue (sendgrid/python-http-client#133), it seems that flask-sendgrid send twice the to parametter after the second request.
sudo pip3 install sendgrid
Answer by Beatrice Dunlap
The Box APIs uses HTTP status codes to communicate if a request
has been successfully processed or not.,Please check our Developer Troubleshooting Articles
for solution to common errors encountered when working with the Box APIs.,Please see the Client Error resource for more details.,Code samples provided under Unilicense
{
"type": "error",
"status": 400,
"code": "bad_digest",
"help_url": "http://developers.box.com/docs/#errors",
"message": "The specified content-md5 did not match what we received",
"request_id": "abcdef123456"
}
Answer by Zahra Salgado
The Client application gets the following response code:,400 Bad request — plain HTTP request sent to HTTPS port,400 Bad request — SSL certificate error,The client application receives an HTTP 400 — Bad request response with the
message «The SSL certificate error». This error is typically sent by the Edge Router
in a two way TLS setup enabled for the incoming connection to Apigee Edge.
The Client application gets the following response code:
HTTP/1.1 400 Bad Request
Followed by the below HTML error page:
<html>
<head>
<title>400 The SSL certificate error</title>
</head>
<body bgcolor="white">
<center> <h1>400 Bad Request</h1>
</center>
<center>The SSL certificate error</center>
<hr>
<center>nginx</center>
</body>
</html>
Typically a virtual host for two-way TLS communication looks as follows:
<VirtualHost name="myTLSVHost">
<HostAliases>
<HostAlias>api.myCompany.com</HostAlias>
</HostAliases>
<Port>443</Port>
<SSLInfo>
<Enabled>true</Enabled>
<ClientAuthEnabled>true</ClientAuthEnabled>
<KeyStore>ref://myKeystoreRef</KeyStore>
<KeyAlias>myKeyAlias</KeyAlias>
<TrustStore>ref://myTruststoreRef</TrustStore>
</SSLInfo>
</VirtualHost>
Once you’ve decided where you would like to capture TCP/IP packets, use the following
tcpdump
command to capture TCP/IP packets:
tcpdump -i any -s 0 host <IP address> -w <File name>
Typically a virtual host for two-way TLS communication looks as follows:
<VirtualHost name="myTLSVHost">
<HostAliases>
<HostAlias>api.myCompany.com</HostAlias>
</HostAliases>
<Port>443</Port>
<SSLInfo>
<Enabled>true</Enabled>
<ClientAuthEnabled>true</ClientAuthEnabled>
<KeyStore>ref://myKeystoreRef</KeyStore>
<KeyAlias>myKeyAlias</KeyAlias>
<TrustStore>ref://myCompanyTruststoreRef</TrustStore>
</SSLInfo>
</VirtualHost>
Typically a virtual host for two-way TLS communication looks as follows:
<VirtualHost name="myTLSVHost">
<HostAliases>
<HostAlias>api.myCompany.com</HostAlias>
</HostAliases>
<Port>443</Port>
<SSLInfo>
<Enabled>true</Enabled>
<ClientAuthEnabled>true</ClientAuthEnabled>
<KeyStore>ref://myKeystoreRef</KeyStore>
<KeyAlias>myKeyAlias</KeyAlias>
<TrustStore>ref://myCompanyTruststoreRef</TrustStore>
</SSLInfo>
</VirtualHost>
openssl
openssl -in <OrgName_envName_vhostName-client.pem> -text -noout
Restart the Router to ensure the latest Certificates are loaded using the below step:
apigee-service edge-router restart
Answer by Ember Nava
The following table lists all the codes that can appear as code attribute of an <error> element if an error has occurred. ,If error messages have been translated, they are returned in the language that’s set in the Accept-Language header of the request. For example, if the headers include Accept-Language: de-de, error messages are returned in German. ,Note: You should not rely on specific text appearing in the <detail> element of an error response. Instead, test the value of the error code attribute to determine why an operation failed.,An HTTP status code of 404 for the response tells you that the operation was not successful because a resource could not be found. In that case, the response body might look like the following example:
For error conditions, the response body also includes an XML block that provides details about the error. For example, if the HTTP response was 404, the response body provides details about what resource in particular was not found. Imagine that you send the following PUT request in order to update information for a user:
http://your-server/api/3.13/sites/9a8b7c6d5-e4f3-a2b1-c0d9-e8f7a6b5c4d/users/9f9e9d9c8-b8a8-f8e7-d7c7-b7a6f6d6e6d
http://your-server/api/3.13/sites/9a8b7c6d5-e4f3-a2b1-c0d9-e8f7a6b5c4d/users/9f9e9d9c8-b8a8-f8e7-d7c7-b7a6f6d6e6d
Answer by Ezra Mora
Errors in Microsoft Graph are returned using standard HTTP status codes, as well as a JSON error response object.,The following table lists and describes the HTTP status codes that can be returned.,The error resource is returned whenever an error occurs in the processing of a request.,The code property contains one of the following possible values. Your apps should be
prepared to handle any one of these errors.
The error response is a single JSON object that contains a single property
named error. This object includes all the details of the error. You can use the information returned here instead of or in addition to the HTTP status code. The following is an example of a full JSON error body.
{
"error": {
"code": "invalidRange",
"message": "Uploaded fragment overlaps with existing data.",
"innerError": {
"requestId": "request-id",
"date": "date-time"
}
}
}
The error resource is composed of these resources:
{
"error": { "@odata.type": "odata.error" }
}
Inside the error response is an error resource that includes the following
properties:
{
"code": "string",
"message": "string",
"innererror": { "@odata.type": "odata.error" }
}
To verify that an error object is an error you are expecting, you must loop
over the innererror
objects, looking for the error codes you expect. For example:
public bool IsError(string expectedErrorCode)
{
OneDriveInnerError errorCode = this.Error;
while (null != errorCode)
{
if (errorCode.Code == expectedErrorCode)
return true;
errorCode = errorCode.InnerError;
}
return false;
}
- Error description
- Short error description in the response
- Example of an error message
If an error occurs, the request processing stops, and the server returns an HTTP response code that identifies the error. In addition to the code, the response contains a short error description.
The error message is returned in the format specified in the request URL after the method name or in the Accept HTTP header.
The error description is passed in the error parameter. This parameter contains the error code (the code parameter) and a short error description (the message parameter).
Code |
Name |
Explanation |
---|---|---|
200 |
OK |
The request is successfully completed. |
206 |
Partial Content |
The request is partially completed. |
400 |
Bad Request |
The request is invalid. |
401 |
Unauthorized |
The request doesn’t include authorization data. |
403 |
Forbidden |
Incorrect authorization data is specified in the request, or access to the requested resource is denied. |
404 |
Not Found |
The requested resource isn’t found. |
405 |
Method Not Allowed |
The requested method isn’t supported for the specified resource. |
415 |
Unsupported Media Type |
The requested content type isn’t supported by the method. |
420 |
Enhance Your Calm |
The resource access restriction is exceeded. |
500 |
Internal Server Error |
Internal server error. Try calling the method after a while. If the error persists, contact the Yandex.Market support service. |
503 |
Service Unavailable |
The server is temporarily unavailable due to high load. Try calling the method after a while. |
-
For the
400 Bad Request
error:Description
Explanation
Possible solution
Collection of field must not be empty
The parameter must not be empty.
Specify at least one element for the parameter.
Invalid status: 'status'
Invalid status is specified.
Check if the sent status is correct for order filtering by status.
JSON: {message}
The JSON data format contains an error.
Check if the data passed in the request body has the correct JSON format.
Missing field
The required parameter isn’t specified.
Specify a value for the required parameter.
The request is too big
The HTTP request size limit is exceeded.
Cut the request size by reducing the amount of the sent data.
Too long time period. Maximum is 'maxPeriod' days
The specified date range is too large. Maximum range — maxPeriod.
Reduce the date range to filter orders by date.
Unexpected character 'character': expected a valid value 'values'
Invalid character.
Check the request body encoding. The required encoding is UTF-8.
Unexpected end of content
The request body ends unexpectedly.
Check if the data passed in the request body has the correct format.
Value / length of field (value) must be between min and max [exclusively]
The parameter value (length) must be between the min and max values and not equal to them.
Check if the parameter value is correct.
Value / length of field (value) must be greater / less than [or equal to] limit
The parameter value (length) must be equal to or greater than (less than) the specified limit value.
Check if the parameter value is correct.
Value of field has too high scale: 'price'
The accuracy of the parameter is set too high.
Set the parameter values with less precision.
Value of field must match the pattern: 'regExp'
The parameter value must match the regular expression.
Check if the parameter value is correct.
XML: {message}
The XML data format contains an error.
Check if the data passed in the request body has the correct XML format.
Other short descriptions that can be found in messages about this error are provided in the descriptions of the corresponding resources.
-
For the
401 Unauthorized
error:Description
Explanation
Possible solution
Unsupported authorization type specified in Authorization header
Authorization type passed in the Authorization HTTP header isn’t supported.
Check if the authorization data is correct.
Authorization header has invalid syntax
The Authorization HTTP header format is incorrect.
Check if the authorization data is correct.
OAuth credentials are not specified
The request doesn’t include authorization data.
Check that the authorization data is correct.
OAuth token is not specified
The request doesn’t include the authorization token (the oauth_token parameter).
Check if the authorization data is correct.
OAuth client id is not specified
The request doesn’t include the application ID (the oauth_client_id parameter).
Check if the authorization data is correct.
-
For the
403 Forbidden
error:Description
Explanation
Possible solution
Access denied
Access to the specified resource is prohibited.
Check if the resource is specified correctly, and if the authorized user login has access to it.
Access to API denied for the client / campaign
The client or store isn’t allowed to access the Yandex.Market Partner API.
Agency clients should contact their agency about getting access to the Yandex.Market Partner API.
Client id is invalid
The specified application ID (the oauth_client_id parameter) is invalid.
Check if the authorization data is correct. If they are correct, get a new app ID, repeat the request with the new authorization data.
Scope is invalid
The specified authorization token (the oauth_token parameter) doesn’t have the necessary set of rights.
Get a new authorization token, mention the right to use the Yandex.Market Partner API when you receive it, and repeat the request with the new authorization data.
Token is invalid
The specified authorization token (parameter oauth_token) is invalid.
Check if the authorization data is correct. If they are correct, get a new authorization token, repeat the request with the new authorization data.
User account is disabled
The user account for which the specified authorization token was issued is blocked.
Contact the Yandex.Market support service.
-
For the
404 Not Found
error:Description
Explanation
Possible solution
Feed not found: 'feedId'
The price list specified in the request isn’t found.
Check if the sent price list ID is correct.
Login not found: 'login'
The username specified in the request isn’t found.
Check if the sent username is correct.
Model not found: 'modelId'
The model specified in the request isn’t found.
Check if the model ID you are passing is correct.
-
For the
405 Method Not Allowed
error:Description
Explanation
Possible solution
Request method 'method' not supported
The requested HTTP method isn’t supported.
Check the methods supported by the resource. You can find the list of methods in the Requests reference section.
-
For the
415 Unsupported Media Type
error:Description
Explanation
Possible solution
Content type 'content-type' not supported
The requested content type isn’t supported.
Pass one of the supported content types.
Missing Content-Type
The content type isn’t specified.
Pass the content type.
Unknown content-type: 'content-type'
The requested content type is unknown.
Pass one of the supported content types.
-
For the
420 Enhance Your Calm
error:Description
Explanation
Possible solution
Hit rate limit of 'N' parallel requests
Exceeded the global limit on the number of simultaneous requests to the Yandex.Market Partner API.
Reduce the number of concurrent requests to the partner API within a single store or partner to N requests.
Hit rate limit of 'N' requests per 'period' for resource 'R'
The resource restriction for the N number of requests to the R resource over the period for the same store or partner is exceeded.
The time until which the limit applies is specified in the X-RateLimit-Resource-Until header. You can use of the resource after the specified time.
-
For the
503 Service Unavailable
error:Description
Explanation
Possible solution
Service temporarily unavailable. Please, try again later
The server is temporarily unavailable due to high load.
Try repeating the request after a while.
Request example:
GET /v2/campaigns.xml HTTP/1.1
Host: api.partner.market.yandex.ru
Accept: */*
Authorization: OAuth oauth_token=,oauth_client_id=b12320932d4e401ab6e1ba43d553d433
Response example:
<response>
<errors>
<error code="UNAUTHORIZED" message="OAuth token is not specified"/>
</errors>
<error code="401">
<message>OAuth token is not specified</message>
</error>
</response>
Request example:
GET /v2/campaigns.json HTTP/1.1
Host: api.partner.market.yandex.ru
Accept: */*
Authorization: OAuth oauth_token=,oauth_client_id=b12320932d4e401ab6e1ba43d553d433
Response example:
{
"errors":
[
{
"code": "UNAUTHORIZED",
"message": "OAuth token is not specified"
}
],
"error":
{
"code": 401,
"message": "OAuth token is not specified"
}
}