Provide Visible Error if <py-env> paths is used in a local HTML file (#311)

* Add onscreen error when using py-env paths in local HTTP files without file server

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Remove redundant code, fix error handling, add 404 error

* Lint and Format

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* manage errors loading files

* use handleFetchError for handling fetch errors in env

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Fabio Pliger <fabio.pliger@gmail.com>
This commit is contained in:
Jeff Glass
2022-05-17 23:48:02 -05:00
committed by GitHub
parent 39774a83c5
commit b767a78b05
8 changed files with 188 additions and 125 deletions

View File

@@ -43,4 +43,42 @@ function guidGenerator(): string {
return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4();
}
export { addClasses, removeClasses, getLastPath, ltrim, htmlDecode, guidGenerator };
/*
* Display a page-wide error message to show that something has gone wrong with
* PyScript or Pyodide during loading. Probably not be used for issues that occur within
* Python scripts, since stderr can be routed to somewhere in the DOM
*/
function showError(msg: string): void {
const warning = document.createElement('div');
warning.style.backgroundColor = 'LightCoral';
warning.style.alignContent = 'center';
warning.style.margin = '4px';
warning.style.padding = '4px';
warning.innerHTML = msg;
document.body.prepend(warning);
}
function handleFetchError(e: Error, singleFile: string){
//Should we still export full error contents to console?
console.warn('Caught an error in loadPaths:\r\n' + e);
let errorContent;
if (e.message.includes('TypeError: Failed to fetch')) {
errorContent = `<p>PyScript: Access to local files
(using "Paths:" in &lt;py-env&gt;)
is not available when directly opening a HTML file;
you must use a webserver to serve the additional files.
See <a style="text-decoration: underline;" href="https://github.com/pyscript/pyscript/issues/257#issuecomment-1119595062">this reference</a>
on starting a simple webserver with Python.</p>`;
} else if (e.message.includes('404')) {
errorContent =
`<p>PyScript: Loading from file <u>` +
singleFile +
`</u> failed with error 404 (File not Found). Are your filename and path are correct?</p>`;
} else {
errorContent =
'<p>PyScript encountered an error while loading from file: ' + e.message + '</p>';
}
showError(errorContent);
}
export { addClasses, removeClasses, getLastPath, ltrim, htmlDecode, guidGenerator, showError, handleFetchError };