Better Errors Exceptions - sgml/signature GitHub Wiki

JavaScript

Uncaught (in promise)

Handle a Promise by making sure there is a catch clause or callback and that the argument passed to the callback is not null, undefined, or ""

RangeError

Change recursive functions to loops

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

Add any prerequisite function calls before the function call that throws the error

URI malformed

Fix the argument to the decodeURIComponent function call

Uncaught SyntaxError: Unexpected token ILLEGAL

There is a mismatched quote

Unexpected token ;

There is a mismatched paren

Uncaught TypeError: Converting circular structure to JSON

Run JSONLint to find the circular reference, then remove it

Error : No ESLint configuration found

Comment out the eslint config code in nuxt.config.js when running yarn link or npm link

WARNING in asset size limit: The following asset(s) exceed the recommended size limit

Image or JS files are too big; replace images with compressed equivalents and split files into components with fewer dependencies

Whitelisted route not detected

Whitelist the undefined route in case the router function returns undefined

Module build failed

There is a component which has a syntax error; remove logic from the HTML markup templates

error An unexpected error occurred: "https://registry.npmjs.org/@foo%2fbar-baz: Not found".

Update the .npmrc file with the new private token: https://blog.npmjs.org/post/118393368555/deploying-with-npm-private-modules

ENOSPC: no space left on device

Out of disk space. Run rm -rf on all repos you no longer use; consider a Raspberry Pi for development

ENOSPC: System limit for number of file watchers reached

No more hot module reloading hooks can be created. Turn off hot module reloading:

    hotMiddleware: {
        client: {
            autoConnect: false,
        },
    },
    indicator: false,

And also via webpack middleware: serverSideRender

DevTools

Error: Extension context invalidated

An extension needs to be disabled

VueJS

error clear vue/*...

The directive is returning a false positive. Add the eslint rule in question to the .eslintrc.js file to turn off the false positive:

  • 'vue/multi-word-component-names': 'off',
  • 'vue/comment-directive': 'off',

Page level error

A component method is failing. Move the method to the store as a getter and reference it as a computed property in the component

this is undefined

Within a VueX store, use context instead

Undefined is returned for a property, but it exists

The object has duplicate key names on two levels, such as data.data. When passing an object, do not wrap it in curly braces

PHP

    

Python

Graphene

must have a sub selection

The query needs a nested block of fields to call the resolver. Update the query in GraphiQL by opening a curly brace after the innermost word or parentheses

"Expecting ':' delimiter: line 1 column 4 (char 3)"

The JSON value in the GraphiQL GUI has a key with no value; remove the empty string \"\" and leave the JSON value as {}

XMLHttpRequest at ... from origin ... has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

The connection has timed out. Try indexing the underlying table, paginating the results, or optimizing the query itself

Need to follow the suggestions listed: indexing, paginate the results or optimize the query

Expected Name, found String "query"...

The GraphQL request headers are not set properly; fix the payload by setting the content-type to application/json and try again

expected type "DateTime", found "2023-9-15T00:00:00"

Pad the month with a leading zero; in JavaScript for example:

String(foo.getUTCMonth()).replace(/^([0-9])$/, "0$1")

CircleCI

ERROR: Could not install packages due to an OSError: [Errno 13] Permission denied: /usr/local/foo.bar

Run the following command to get ownership of the directory where permission is denied: sudo chown -R circleci:circleci /usr/local

cannot import name 'soft_unicode' from 'markupsafe'

Check the changelog to see when soft_unicode was removed (https://github.com/aws/aws-sam-cli/issues/3661)

cannot import name 'URL' from 'sqlalchemy.engine'

If running on CI, update the requirements.txt to trigger a new version of SQLAlchemy to be downloaded. If running locally, copy the code from the source repo: https://github.com/sqlalchemy/sqlalchemy/blob/main/lib/sqlalchemy/engine/__init__.py into the venv module:

vi ./env/lib/python3.7/site-packages/sqlalchemy/engine/__init__.py
from .url import URL as URL

FATAL ERROR: Reached heap limit Allocation failed - JavaScript heap out of memory

The bundle is too large. Use the depcheck module to slim down the size of the package: https://www.npmjs.com/package/depcheck. Also, remove the tmp/node-jiti directory and add export NODE_OPTIONS=--max_old_space_size=4096 to your .bashrc

Postgresql

E: Package 'pgadmin4' has no installation candidate

Find the path:/usr/pgadmin4/bin/pgadmin4 Add the path to a function: function pgadmin(){/usr/pgadmin4/bin/pgadmin4} Run the function

pgadmin: server could not be contacted

Configure the web server for pgadmin: sudo /usr/pgadmin4/bin/setup-web.sh

/usr/pgadmin4/bin/setup-web.sh: line 75: /usr/pgadmin4/venv/bin/python3: No such file or directory Error setting up server mode. Please examine the output above.

The path to python cannot be found. Update the virtualenv symbolic link:

cd /usr/pgadmin4/venv/bin
sudo unlink python3
sudo ln -s /usr/bin/python3.14 python3

No module named typer Go to pgadmin directory and start the virtualenv. Install the module named typer

cd /usr/pgadmin4
source venv/bin/activate
pip install typer

ModuleNotFoundError: No module named 'pip'

Multiple installations of pip; do not use sudo with pip

Linux

Syntax error near unexpected token

A whitespace character is found where an underscore is expected in a .bashrc or .profile file

Dbeaver: Cannot open display:

Set the display by adding the following to your bashrc: export DISPLAY=:0.0

Localhost

redirectUrl=undefined

The redirectUrl is an environment variable; make sure the .env file is defined, or copy it: cp .env.local .env

ModuleNotFoundError: no module named ...

The virtualenv is not setup: python3 -m venv env or the module itself is not installed poetry add ...=123 or pip install ...@123

Invalid Header padding

The value of the Bearer token is missing the inital character, ey for example

Unauthorized: could not verify token, AUTH: could not extract headers from token: null

The token has not been created or the decode method has been called on the JWT string; use hasattr to avoid this

python3 is already the newest version

Python3 is not available on the package manager for this OS; install python manually;

confluent-kafka-python requires librdkafka v1.6.0 or later

Lower the version of confluent-kafka-python to one the depends on librdkafka < 1.0.0

SyntaxError Invalid syntax: print(f"{self.foo}")

Upgrade python or switch to a newer version via virtualenv

Invalid URL 'None/warmer': No schema supplied. Perhaps you meant http://None/warmer?

Add the variable the evals to None to the environment

glob.glob returns nothing

Run python from the root of the repo; DO NOT cd into the directory of the python script; glob drills down from the current directory

Unexpected EOF while parsing

Remove unindented whitespace at the end of the file below the last def or class declaration

utils is not a package

Add if __name__ == '__main__': for running the module from the shell

ERROR: Cannot install -r /root/.cache/serverless-python-requirements/24a3f062a8ff9c9ab2e069aa76d73f32dc17014ed59b0925194e0b6769716f5b_x86_64_slspyc/requirements.txt (line 22) and loguru==0.5.2 because these package versions have conflicting dependencies.

Update the underlying requirements.txt or poetry.lock files to make sure any cached dependencies are updated. Use poetry lock --no-update to do so without upgrading packages

KeyError: 'production'

The name is not one of the keys within the dictionary; look at the dictionary to see which key names are defined, and change your variable name to match

TypeError: string indices must be integers

If you know the method signature, then the type returned by a nested function is wrong If you do not know the method signature, then pass a list or an array rather than a dict or object

UnboundLocalError: local variable 'foo' referenced before assignment

Define the variable a default value outside of an if statement

pg_config not found

Postgres library and python bindings are not installed. Run the following:

sudo apt-get install libpq-dev
pip install psycopg2-binary

Permission denied: '/usr/local/LICENSE.txt'

The git:// URL is pointed to a branch using the @ syntax; remove that syntax and hotfix the main branch

'ResultProxy' object is not subscriptable

The resultset is a iterable object which needs to be converted into a list:

resultset = [dict(row) for row in res]
print resultset

tuple index out of range

The number of indices in the tuple does not match the method signature

AttributeError: module 'logging' has no attribute 'getLogger'

Circular import of a file(logging.py) or directory(logging/__init.py) named logging. Rename the file or directory in question to resolve this

AttributeError: 'function' object has no attribute 'trace'

The wrapper function is not returning the method itself, it is calling it. Change the return value to fix this

Running setup.py install for cffi ... error

libffi is not installed. Run apt-cache search libffi | grep dev, then install one of the packages

Invalid principal in policy: "SERVICE":"states.#{AWS::Region}.amazonaws.com"

The variable is not being interpreted; use a different syntax; search for examples on Github

Serverless plugin "serverless-python-requirements" not found

Install the plugin:

sls plugin install -n serverless-python-requirements -p 8000 --stage develop 

Confirm it is installed:

npm list | grep serverless

SQL Constraint Violation

XRef the metadata to make sure the any key/value pairs that reference other tables is valid

Remove manually entered metadata which may fail silently

SQLAlchemy Invalidrequesterror:

Fix the constructor call that references the table class to use named parameters

column cons.consrc

Downgrade Postgres from 12 to 11

could not identify an equality operator for type json

If using a JSONB column in a GROUP BY clause, use the #>> followed by a list of ordered keys to search in the JSON '{0, parent, child}' (https://stackoverflow.com/questions/39261409/postgres-group-by-on-jsonb-inner-field)

InFailedSqlTransaction ... VALUES (nextval(...))

The sequence name is wrong; find the correct name in the sequences view of the current db(https://www.postgresql.org/docs/10/view-pg-sequences.html

TypeError: 'Response' object is not subscriptable

The JSON serialization of the Response is not the default, use foo.get_json() to return the subscriptable format

pytest test failed

Add a print statement and raise an exception to debug from there:

foo = client.get("example.com")
print(f"foo: {repr(foo)}")
raise Exception("bar")

AttributeError: 'Flask' object has no attribute 'InvalidUsage':

The request JSON is improperly formatted

werkzeug routing error at the beginning of the stack trace

Upgrade from 0.15.4 to to a later version.

AttributeError: 'NoneType' object has no attribute 'get_meta':

If SQLAlchemy, the query returned no records; otherwise the dot notation parent object does not exist

TypeError: argument of type 'NoneType' is not iterable

A list is expected, but the value is None; trace the method calls to the one which maps keys to values via a dict or a yaml config and make sure each key exists

Cannot parse "serverless.yml": bad indentation of a mapping entry in "/root/repo/serverless.yml" (149:21)

Check indentation using the yamlpath module:

pip install yamlpath
yaml-validate /path/to/any/files.yaml

TypeError: Object of type BaseQuery is not JSON serializable:

Object needs to be iterated through and appended to a list

TypeError: Object of type datetime is not JSON serializable

Convert to isoformat:

def serialize_date(x):
    if isinstance(x, datetime.datetime):
        return x.isoformat()
raise TypeError("Unknown type")

sqlalchemy.exc.InvalidRequestError: Table 'XXXX' is already defined for this MetaData instance:

The sqlalchemy Class for this table is duplicated; comment it out the Class definition to see the real error;

TypeError: check_vendor() takes 2 positional arguments but 3 were given:

self needs to be added to the args list and you need to instantiate the Class

TypeError: 'dict' object is not callable The view function did not return a valid response

Return a valid JSON object rather than a dictionary from the method bound to the route

Parameter validation failed:\nInvalid type for parameter SecretId, value: None, type: <class 'NoneType'>

The environment variable is not defined; define it and restart the server

Secrets Manager can't find the specified secret.

The environment variable FOO has a value that not match the name in Secrets Manager. Use echo $FOO to check, and unset FOO to delete

Exception: uuid not found: 5ece90e9-a37f-464b-8deb-291f7d91636e

Add this uuid to the table in question

'UUID' object has no attribute 'openapi_types'

Use str(foo_uuid) to convert the UUID from an object to a string

TypeError: byte indices must be integers or slices, not str

Convert the HTTP byte stream to JSON, using .json() for requests or .get_json() for Flask. Use foo.keys() to check for a key before referencing it, e.g. foo["bar"]

JSONDecodeError: Expecting value

Check the status code of the response, and only assume it is JSON if it returns 200

unhashable type

The type of data you expect is really a string; add a try/except block when assigning its value and use len() and type() to see the data that's actually returned

Unmatched quote

The string literal needs double quotes with nested single quotes or vice versa: """select foo from bar where foo like '%{baz}%' """

IndexError: list index out of range

Use len in a range check before referencing the list in a for loop:

for name in range(len(names)):

Do an existence check on the list before referencing its index, then default if it does not exist:

if foo:
    bar = foo[0]
else:
    bar = {}

TypeError: 'NoneType' object is not subscriptable

The list index cannot be referenced because the object type is None, not list. Add a length check to foo[0]:

if instance(foo, list): if len(foo) > 0: return foo[0]

TypeError: Failed to fetch

Either the mutation has a syntax error, or the server is no longer running; check the logs, then fix the error or restart the server

name 'bop' is not defined

Nest try/except blocks to suppress: try: try: bop except Exception as e: print(e) except Exception as e: print(e)

E0001: invalid syntax (, line ###)

Nested double quotes or some other error, use syntax highlighter to find the root cause

foo is an invalid keyword argument for Bar

If Bar is the model of a database table, the arg name does not match the column name. Update the arg name to match the column name

mutate() got an unexpected keyword argument 'foo'

Add 'foo' into the signature of the mutate method corresponding to the class where the foo is instantiated

ConnectionResetError

Change power management settings to avoid suspending your machine when it is idle

AttributeError: '_AppCtxGlobals' object has no attribute '_foo'

g._foo is not defined as an attribute in the global object. Hardcode it in init.py.

"The 'hubspot-api-client' distribution was not found and is required by the application"

Check the install pip requirements section in the build logs; bump the version of the package to clear the local cache

ImportError: cannot import name 'PROTOCOL_TLS'

Version of urllib3 is no longer available on pypi. Goto pypi.org, find the latest version, then upgrade urllib3:

pip install --upgrade urllib3

botocore exceptions

Invalid type for parameter SecretId

  1. Run the framework server sls wsgi serve --stage develop rather than the flask server

  2. The environment variable doesn't exist; add it to your bashrc or CI env vars; look for os.getenv('*secret') calls and cross-reference the names with secretsmanager e.g. FOO_SECRET=/foo/bar/baz

Alembic

Can't locate revision identified by '916aeb895155'

Clear the revision out of the alembic_version table; replace it with the version that you want to revert to; if that works, but the table itself is altered, then explicitly copy the files to the alembic /versions folder

(psycopg2.errors.DuplicateColumn)

If the upgrade already suceeded, then drop the table and redeploy

FAILED: Destination 7bedd7e947ad is not a valid downgrade target from current head(s)

Run alembic current; if it is an empty string, then:

  • run alembic history | less to get the head revision, for instance 999999
  • then run alembic stamp 999999

Axios

TypeError: Cannot read property 'includes' of undefined

The constant from the .env file used by the index.js store is undefined; update the .env file to include it

PNPM

This @babel/plugin-proposal-private-property-in-object version is not meant to be imported. Something is importing @babel/plugin-proposal-private-property-in-object without declaring it in its dependencies (or devDependencies) in the package.json file.

Remove the lockfile and set node_modules to hoist in your .npmrc. For example, via pnpm:

shamefully-hoist=true lockfile=false

Yarn

FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory

Run without tailwind; remove it from package.json, *.js, and *.css files: https://shopify.github.io/hydrogen-v1/tutorials/css-support/remove-tailwind

Slowness

Upgrade to yarn 2: https://yarnpkg.com/getting-started/migration

JavaScript heap out of memory

Too many runtime dependencies. Turn off the Tailwind just-in-time (JIT) compiler

Gyp error

Run yarn config list and check the python version. If it is outdated, use yarn set config to point to the latest python executable on your machine

error An unexpected error occurred: "/root/repo/package.json: Unexpected token < in JSON at position 2"

Run git checkout -p to merge a clean package.json

Error: Node Sass does not yet support your current environment: Linux 64-bit with Unsupported runtime (93)

Change the node version. Use nvm for easy access to multiple versions of node

DeprecationWarning: Use of deprecated folder mapping "./" in the "exports" field module resolution of the package at foo/package.json

Add the package explicitly: pnpm add foo

node_modules/.bin/eslint foo.vue Oops...

Run eslint with the reference to the target file explicitly given using the absolute path:

yarn run eslint --ext ".vue" ~/fii-org/web.support/components/Household.vue

Can't resolve module bar for foo

Open the node_modules/foo/package.json, move the dependency bar to the peerDependencies block, manually install the tarball using the npm URL(https://registry.npmjs.org/bar/latest), wget, and tar -xvf bar.tgz. Reload or wait for the hot reload

require-from-eslint.js not supported

Update the.eslintrc.js file to use the new parser: parser: '@babel/eslint-parser'

ValidationError: Invalid options object

Run yarn install first before running yarn run

CI build suceeds, but local build fails Use the build log to run yarn locally with the same arguments as CI uses, for example if no lockfile is used in CI, then clear your node_modules and reinstll all modules:

rm -rf ./node_modules
yarn install --no-lockfile

Error: Spawn node-gyp ENOENT

node-gyp is not installed; run sudp apt-get install -y node-gyp then retry

node-gyp print error

sudo apt-get install python2-7 yarn config set python /usr/bin/python2.7

gyp ERR! node -v v16.13.1 gyp ERR! node-gyp -v v3.8.0 gyp ERR! not ok

Version mismatch between node and node-gyp; use nvm to switch to an older node version: nvm use v12.23

404 for scoped private package

Use git clone to download the private source, run npm link in the repo root path, then run npm link @foo/bar in the main repo root path and remove the dependencies from the package.json file

Cannot find @babel/compat-data Install it using a forward slash to escape the backslash and an older version:

yarn add @babel\/[email protected]

Then confirm the module exists:

cd node_modules
cd @babel/compat-data
ls

And run npm link in the directory, then npm link @babel/compat-data in the directory where it failed

NPM

expecting a function but got [object Object]

Newer JS syntax in a dependency module is conflicting with old JS syntax in a dependent module

rm -rf ./node_modules
rm -rf ~/.node_modules
sudo npm uninstall -g serverless
npm install

Nuxt

Error: Child compilation failed

Switching branches in git has caused a mismatch between the source and the compiled objects. Stop nuxt, kill the node process, remove the .nuxt folder, and run yarn build. Then run yarn run dev

Module parse failed: Unexpected token... You may need an appropriate loader to handle

Update nuxt.config.js by adding the transpile option. In there, copy and paste the name of the packages which need to be transpiled from the node-modules error message into an array. For example:

   profile: true,
   cssSourceMap: false,
   transpile: ['query-string','filter-obj'],

@foo not found in registry.npmjs.org

Package foo has been delisted from npmjs, so a replacement package needs to be found and integrated into the project.

Vue packages version mismatch: [email protected] [email protected]

  • See the root cause of the problem: grep vue-server-renderer *
  • Remove the root cause: rm pnpm-lock.yaml
  • Prevent it from happening again: pnpm install --frozen-lockfile
  • Fix it explicitly: pnpm add [email protected]
  • Rerun the build: pnpm run build

Permissions error. Clone the repo and run yarn link in the repo, then run yarn link "@foo" in the web project

Module build failed (from ./node_modules/vue-loader/lib/loaders/stylePostLoader.js): TypeError: Cannot read property 'spaces' of undefined TypeError: Cannot read properties of undefined (reading 'styles') at Object.loader (/home/think/fii-org/web.ops/node_modules/.pnpm/[email protected][email protected][email protected]/node_modules/vue-loader/dist/index.js:96:34)

The version of vue-loader is newer than the version of webpack, so you need to downgrade it to make the API signatures match. Find a vue-loader version via npm using the tag history

vue-loader vue-style-loader "TypeError: Cannot read properties of undefined (reading 'styles')" Downgrade vue-loader to the next lower major version; rebuild; repeat until it works

CSS Loader has been initialized using an options object that does not match the API schema

Downgrade the css-loader to an older version: `pnpm add

Vue

window.foo is undefined

If a component is declaring something in the global scope, a hanging comma may be the issue. Run eslint and prettier on the component and the page that references it

Template Not Found

The component defined in the index.vue file of the route is not defined properly; try a minimal <script> tag content such as: export default { name: 'foo' }

Unknown custom element: - did you register the component correctly

A component Foo needs:

  • A export statement with a name in its foo.vue file: `export default { name: 'FundTransactions' }
  • An import statement in a parent component: import Foo from '~/components/Foo.vue'
  • An object literal which declares the component components: { Foo } from a parent component

VueX

Do not mutate vuex store state outside mutation handlers

You need to call an action to update the state properly. Update the data using map/filter/etc in the axios callback, copy the key/value pairs into a new object in the component method, or use Object.defineProperty in the store getter to workaround this

Property or method "foo" is not defined on the instance but referenced during render

Your property is set in state, but not in a getter. Refresh the page after the change.

Localhost Docker Server

Can't open "extfile.cnf" for reading, No such file or directory

This error usually occurs when the extfile.cnf file is not found in the expected location or is not properly formatted Make sure the file is in the correct location and contains only two lines: subjectAltName = DNS:... and extendedKeyUsage = Also, ensure that the file is in UTF-8 format

Failed to start daemon: error while opening volume store metadata database (/var/lib/docker/volumes/metadata.db): timeout

You can try stopping all Docker processes and then restarting Docker. Use ps -aux | grep docker to get all docker processes.

Failed to initialize: failed to retrieve context tls info: tls: failed to find any PEM data in certificate input

If the key file has issues, you might need to add an empty line at the top of the file4.

Unable to configure handler 'Processor'

The path to the log file needs to be updated to be within the docker container. Look for a default path that starts with ~/ or home and change it

Localhost Flask Server

ERROR: graphql endpoint: http://localhost:5000/graphql status code: 405 The endpoint defined for the Graphene server is incorrect. Update the corresponding ENV variable to point to the correct endpoint

Localhost NodeJS Server

localhost://3000localhost:8000 URLs in the Network panel

A .env URL is missing the //. change it from http:8000 to http://8000

Loading status bar message stays forever

Kill all the node processes

Google Auth does not redirect

Incognito Mode does not work with Google Auth

path not found

PATH=${PATH%:\/home\/wrong\/dir\/}

404s

NPM Module not found...

Bad defaults. Add the private token. Also, remove registry.npmjs.com from .npmrc if you're using a private registry

Nuxt/Next JS Import not found...

Wrong package version downloaded. Use foo@ver to download the exact version with the import you need. Use the CI build logs to find the version that works

Localhost VM

VERR_INTNET_FLT_IF_NOT_FOUND

Enable the Virtual Network Adapter or run docker-machine create foo to start from scratch

Is the server running on host "localhost" (127.0.0.1) and accepting connections on TCP/IP ####

Start forwarding the port in question

Web Server

500 for index.html

.htaccess is using a directive that is not allowed in that file, but it only allowed in httpd.conf

403 forbidden for all files

SymLinksIfOwnerMatch is set as an option; comment it out

No connection could be made because the target machine actively refused it

Set the host and port using different combinations, such as:

  1. Use 127.0.0.1 as database host, and port 3308 for MySQL 8+
  2. Use 127.0.0.1 as the database host, and port 5432 for Postgres 11+

ERR_TOO_MANY_REDIRECTS

Cookies are disabled. If this is on purpose, use a browser such as Lynx which is text-based for testing

JS

process.on('uncaughtException', (err) => {
    console.error('Uncaught exception:', err);
    // Add your desired behavior here (e.g., logging, handling the error).
});

// Trigger an error (for testing)
throw new Error('This is a custom error');

Ruby

Perl

#!/usr/bin/perl
use strict;
use warnings;

sub custom_die_handler {
    my ($message) = @_;
    print "Custom die handler: $message\n";
    # Add your desired behavior here (e.g., logging, handling the error).
}

# Set the custom die handler
$SIG{__DIE__} = \&custom_die_handler;

# Trigger an error (for testing)
die "This is a custom error";

# Rest of your Perl code...

Golang

Marshmallow

Virtualbox

AWS

"Your multi-factor authentication (MFA) token might be out of sync with our server. Enter two consecutive token codes below to resync it."

Don't copy the MFA app from one device to another. Register each device separately

Unable to apply step "error" to input

The input is an array, so dereference the index by changing $.error to $[0].error

Unable to import app.app

The lockfile and the pip dependencies are out of sync. Re-deploy the code and compare to other branches to fix this

⚠️ **GitHub.com Fallback** ⚠️