Skip to content

Instantly share code, notes, and snippets.

@walkness
Last active January 11, 2017 20:10
Show Gist options
  • Save walkness/44a630ec06ae7c761b4da8cbc6a0dfd9 to your computer and use it in GitHub Desktop.
Save walkness/44a630ec06ae7c761b4da8cbc6a0dfd9 to your computer and use it in GitHub Desktop.
Simple function to process DRF errors in JS
function processServerError(error, fields) {
const fieldErrors = {};
let otherErrors = [];
if (typeof error === 'object') {
for (const field of fields) {
const value = error[field];
if (value) {
if (value.constructor === {}.constructor) {
Object.keys(value).forEach(key => {
fieldErrors[`${field}.${key}`] = value[key];
});
} else {
fieldErrors[field] = error[field];
}
delete error[field];
}
}
if (Object.keys(error).length > 0) {
Object.keys(error).forEach(item => {
if (item === 'detail') {
otherErrors.push(error[item]);
} else {
otherErrors.push(`${item}: ${error[item]}`);
}
});
}
} else {
otherErrors = [error];
}
if (Object.keys(fieldErrors).length === 0 && otherErrors.length === 0) {
otherErrors.push('An unknown error occurred. Please try again.');
}
return {
fields: fieldErrors,
other: otherErrors,
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment