Last active
January 11, 2017 20:10
-
-
Save walkness/44a630ec06ae7c761b4da8cbc6a0dfd9 to your computer and use it in GitHub Desktop.
Simple function to process DRF errors in JS
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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