1633781100
JavaScript 12 - dars | Interaktiv JavaScript | kurs seriyasi
✅ Comparison Operators (Taqqoslash operatorlari)
1659283860
ActiveInteraction manages application-specific business logic. It's an implementation of service objects designed to blend seamlessly into Rails.
ActiveInteraction gives you a place to put your business logic. It also helps you write safer code by validating that your inputs conform to your expectations. If ActiveModel deals with your nouns, then ActiveInteraction handles your verbs.
Add it to your Gemfile:
gem 'active_interaction', '~> 5.1'
Or install it manually:
$ gem install active_interaction --version '~> 5.1'
This project uses Semantic Versioning. Check out GitHub releases for a detailed list of changes.
To define an interaction, create a subclass of ActiveInteraction::Base
. Then you need to do two things:
Define your inputs. Use class filter methods to define what you expect your inputs to look like. For instance, if you need a boolean flag for pepperoni, use boolean :pepperoni
. Check out the filters section for all the available options.
Define your business logic. Do this by implementing the #execute
method. Each input you defined will be available as the type you specified. If any of the inputs are invalid, #execute
won't be run. Filters are responsible for checking your inputs. Check out the validations section if you need more than that.
That covers the basics. Let's put it all together into a simple example that squares a number.
require 'active_interaction'
class Square < ActiveInteraction::Base
float :x
def execute
x**2
end
end
Call .run
on your interaction to execute it. You must pass a single hash to .run
. It will return an instance of your interaction. By convention, we call this an outcome. You can use the #valid?
method to ask the outcome if it's valid. If it's invalid, take a look at its errors with #errors
. In either case, the value returned from #execute
will be stored in #result
.
outcome = Square.run(x: 'two point one')
outcome.valid?
# => nil
outcome.errors.messages
# => {:x=>["is not a valid float"]}
outcome = Square.run(x: 2.1)
outcome.valid?
# => true
outcome.result
# => 4.41
You can also use .run!
to execute interactions. It's like .run
but more dangerous. It doesn't return an outcome. If the outcome would be invalid, it will instead raise an error. But if the outcome would be valid, it simply returns the result.
Square.run!(x: 'two point one')
# ActiveInteraction::InvalidInteractionError: X is not a valid float
Square.run!(x: 2.1)
# => 4.41
ActiveInteraction checks your inputs. Often you'll want more than that. For instance, you may want an input to be a string with at least one non-whitespace character. Instead of writing your own validation for that, you can use validations from ActiveModel.
These validations aren't provided by ActiveInteraction. They're from ActiveModel. You can also use any custom validations you wrote yourself in your interactions.
class SayHello < ActiveInteraction::Base
string :name
validates :name,
presence: true
def execute
"Hello, #{name}!"
end
end
When you run this interaction, two things will happen. First ActiveInteraction will check your inputs. Then ActiveModel will validate them. If both of those are happy, it will be executed.
SayHello.run!(name: nil)
# ActiveInteraction::InvalidInteractionError: Name is required
SayHello.run!(name: '')
# ActiveInteraction::InvalidInteractionError: Name can't be blank
SayHello.run!(name: 'Taylor')
# => "Hello, Taylor!"
You can define filters inside an interaction using the appropriate class method. Each method has the same signature:
Some symbolic names. These are the attributes to create.
An optional hash of options. Each filter supports at least these two options:
default
is the fallback value to use if nil
is given. To make a filter optional, set default: nil
.
desc
is a human-readable description of the input. This can be useful for generating documentation. For more information about this, read the descriptions section.
An optional block of sub-filters. Only array and hash filters support this. Other filters will ignore blocks when given to them.
Let's take a look at an example filter. It defines three inputs: x
, y
, and z
. Those inputs are optional and they all share the same description ("an example filter").
array :x, :y, :z,
default: nil,
desc: 'an example filter' do
# Some filters support sub-filters here.
end
In general, filters accept values of the type they correspond to, plus a few alternatives that can be reasonably coerced. Typically the coercions come from Rails, so "1"
can be interpreted as the boolean value true
, the string "1"
, or the number 1
.
In addition to accepting arrays, array inputs will convert ActiveRecord::Relation
s into arrays.
class ArrayInteraction < ActiveInteraction::Base
array :toppings
def execute
toppings.size
end
end
ArrayInteraction.run!(toppings: 'everything')
# ActiveInteraction::InvalidInteractionError: Toppings is not a valid array
ArrayInteraction.run!(toppings: [:cheese, 'pepperoni'])
# => 2
Use a block to constrain the types of elements an array can contain. Note that you can only have one filter inside an array block, and it must not have a name.
array :birthdays do
date
end
For interface
, object
, and record
filters, the name of the array filter will be singularized and used to determine the type of value passed. In the example below, the objects passed would need to be of type Cow
.
array :cows do
object
end
You can override this by passing the necessary information to the inner filter.
array :managers do
object class: People
end
Errors that occur will be indexed based on the Rails configuration setting index_nested_attribute_errors
. You can also manually override this setting with the :index_errors
option. In this state is is possible to get multiple errors from a single filter.
class ArrayInteraction < ActiveInteraction::Base
array :favorite_numbers, index_errors: true do
integer
end
def execute
favorite_numbers
end
end
ArrayInteraction.run(favorite_numbers: [8, 'bazillion']).errors.details
=> {:"favorite_numbers[1]"=>[{:error=>:invalid_type, :type=>"array"}]}
With :index_errors
set to false
the error would have been:
{:favorite_numbers=>[{:error=>:invalid_type, :type=>"array"}]}
Boolean filters convert the strings "1"
, "true"
, and "on"
(case-insensitive) into true
. They also convert "0"
, "false"
, and "off"
into false
. Blank strings will be treated as nil
.
class BooleanInteraction < ActiveInteraction::Base
boolean :kool_aid
def execute
'Oh yeah!' if kool_aid
end
end
BooleanInteraction.run!(kool_aid: 1)
# ActiveInteraction::InvalidInteractionError: Kool aid is not a valid boolean
BooleanInteraction.run!(kool_aid: true)
# => "Oh yeah!"
File filters also accept TempFile
s and anything that responds to #rewind
. That means that you can pass the params
from uploading files via forms in Rails.
class FileInteraction < ActiveInteraction::Base
file :readme
def execute
readme.size
end
end
FileInteraction.run!(readme: 'README.md')
# ActiveInteraction::InvalidInteractionError: Readme is not a valid file
FileInteraction.run!(readme: File.open('README.md'))
# => 21563
Hash filters accept hashes. The expected value types are given by passing a block and nesting other filters. You can have any number of filters inside a hash, including other hashes.
class HashInteraction < ActiveInteraction::Base
hash :preferences do
boolean :newsletter
boolean :sweepstakes
end
def execute
puts 'Thanks for joining the newsletter!' if preferences[:newsletter]
puts 'Good luck in the sweepstakes!' if preferences[:sweepstakes]
end
end
HashInteraction.run!(preferences: 'yes, no')
# ActiveInteraction::InvalidInteractionError: Preferences is not a valid hash
HashInteraction.run!(preferences: { newsletter: true, 'sweepstakes' => false })
# Thanks for joining the newsletter!
# => nil
Setting default hash values can be tricky. The default value has to be either nil
or {}
. Use nil
to make the hash optional. Use {}
if you want to set some defaults for values inside the hash.
hash :optional,
default: nil
# => {:optional=>nil}
hash :with_defaults,
default: {} do
boolean :likes_cookies,
default: true
end
# => {:with_defaults=>{:likes_cookies=>true}}
By default, hashes remove any keys that aren't given as nested filters. To allow all hash keys, set strip: false
. In general we don't recommend doing this, but it's sometimes necessary.
hash :stuff,
strip: false
String filters define inputs that only accept strings.
class StringInteraction < ActiveInteraction::Base
string :name
def execute
"Hello, #{name}!"
end
end
StringInteraction.run!(name: 0xDEADBEEF)
# ActiveInteraction::InvalidInteractionError: Name is not a valid string
StringInteraction.run!(name: 'Taylor')
# => "Hello, Taylor!"
String filter strips leading and trailing whitespace by default. To disable it, set the strip
option to false
.
string :comment,
strip: false
Symbol filters define inputs that accept symbols. Strings will be converted into symbols.
class SymbolInteraction < ActiveInteraction::Base
symbol :method
def execute
method.to_proc
end
end
SymbolInteraction.run!(method: -> {})
# ActiveInteraction::InvalidInteractionError: Method is not a valid symbol
SymbolInteraction.run!(method: :object_id)
# => #<Proc:0x007fdc9ba94118>
Filters that work with dates and times behave similarly. By default, they all convert strings into their expected data types using .parse
. Blank strings will be treated as nil
. If you give the format
option, they will instead convert strings using .strptime
. Note that formats won't work with DateTime
and Time
filters if a time zone is set.
Date
class DateInteraction < ActiveInteraction::Base
date :birthday
def execute
birthday + (18 * 365)
end
end
DateInteraction.run!(birthday: 'yesterday')
# ActiveInteraction::InvalidInteractionError: Birthday is not a valid date
DateInteraction.run!(birthday: Date.new(1989, 9, 1))
# => #<Date: 2007-08-28 ((2454341j,0s,0n),+0s,2299161j)>
date :birthday,
format: '%Y-%m-%d'
DateTime
class DateTimeInteraction < ActiveInteraction::Base
date_time :now
def execute
now.iso8601
end
end
DateTimeInteraction.run!(now: 'now')
# ActiveInteraction::InvalidInteractionError: Now is not a valid date time
DateTimeInteraction.run!(now: DateTime.now)
# => "2015-03-11T11:04:40-05:00"
date_time :start,
format: '%Y-%m-%dT%H:%M:%S'
Time
In addition to converting strings with .parse
(or .strptime
), time filters convert numbers with .at
.
class TimeInteraction < ActiveInteraction::Base
time :epoch
def execute
Time.now - epoch
end
end
TimeInteraction.run!(epoch: 'a long, long time ago')
# ActiveInteraction::InvalidInteractionError: Epoch is not a valid time
TimeInteraction.run!(epoch: Time.new(1970))
# => 1426068362.5136619
time :start,
format: '%Y-%m-%dT%H:%M:%S'
All numeric filters accept numeric input. They will also convert strings using the appropriate method from Kernel
(like .Float
). Blank strings will be treated as nil
.
Decimal
class DecimalInteraction < ActiveInteraction::Base
decimal :price
def execute
price * 1.0825
end
end
DecimalInteraction.run!(price: 'one ninety-nine')
# ActiveInteraction::InvalidInteractionError: Price is not a valid decimal
DecimalInteraction.run!(price: BigDecimal(1.99, 2))
# => #<BigDecimal:7fe792a42028,'0.2165E1',18(45)>
To specify the number of significant digits, use the digits
option.
decimal :dollars,
digits: 2
Float
class FloatInteraction < ActiveInteraction::Base
float :x
def execute
x**2
end
end
FloatInteraction.run!(x: 'two point one')
# ActiveInteraction::InvalidInteractionError: X is not a valid float
FloatInteraction.run!(x: 2.1)
# => 4.41
Integer
class IntegerInteraction < ActiveInteraction::Base
integer :limit
def execute
limit.downto(0).to_a
end
end
IntegerInteraction.run!(limit: 'ten')
# ActiveInteraction::InvalidInteractionError: Limit is not a valid integer
IntegerInteraction.run!(limit: 10)
# => [10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0]
When a String
is passed into an integer
input, the value will be coerced. A default base of 10
is used though it may be overridden with the base
option. If a base of 0
is provided, the coercion will respect radix indicators present in the string.
class IntegerInteraction < ActiveInteraction::Base
integer :limit1
integer :limit2, base: 8
integer :limit3, base: 0
def execute
[limit1, limit2, limit3]
end
end
IntegerInteraction.run!(limit1: 71, limit2: 71, limit3: 71)
# => [71, 71, 71]
IntegerInteraction.run!(limit1: "071", limit2: "071", limit3: "0x71")
# => [71, 57, 113]
IntegerInteraction.run!(limit1: "08", limit2: "08", limit3: "08")
ActiveInteraction::InvalidInteractionError: Limit2 is not a valid integer, Limit3 is not a valid integer
Interface filters allow you to specify an interface that the passed value must meet in order to pass. The name of the interface is used to look for a constant inside the ancestor listing for the passed value. This allows for a variety of checks depending on what's passed. Class instances are checked for an included module or an inherited ancestor class. Classes are checked for an extended module or an inherited ancestor class. Modules are checked for an extended module.
class InterfaceInteraction < ActiveInteraction::Base
interface :exception
def execute
exception
end
end
InterfaceInteraction.run!(exception: Exception)
# ActiveInteraction::InvalidInteractionError: Exception is not a valid interface
InterfaceInteraction.run!(exception: NameError) # a subclass of Exception
# => NameError
You can use :from
to specify a class or module. This would be the equivalent of what's above.
class InterfaceInteraction < ActiveInteraction::Base
interface :error,
from: Exception
def execute
error
end
end
You can also create an anonymous interface on the fly by passing the methods
option.
class InterfaceInteraction < ActiveInteraction::Base
interface :serializer,
methods: %i[dump load]
def execute
input = '{ "is_json" : true }'
object = serializer.load(input)
output = serializer.dump(object)
output
end
end
require 'json'
InterfaceInteraction.run!(serializer: Object.new)
# ActiveInteraction::InvalidInteractionError: Serializer is not a valid interface
InterfaceInteraction.run!(serializer: JSON)
# => "{\"is_json\":true}"
Object filters allow you to require an instance of a particular class or one of its subclasses.
class Cow
def moo
'Moo!'
end
end
class ObjectInteraction < ActiveInteraction::Base
object :cow
def execute
cow.moo
end
end
ObjectInteraction.run!(cow: Object.new)
# ActiveInteraction::InvalidInteractionError: Cow is not a valid object
ObjectInteraction.run!(cow: Cow.new)
# => "Moo!"
The class name is automatically determined by the filter name. If your filter name is different than your class name, use the class
option. It can be either the class, a string, or a symbol.
object :dolly1,
class: Sheep
object :dolly2,
class: 'Sheep'
object :dolly3,
class: :Sheep
If you have value objects or you would like to build one object from another, you can use the converter
option. It is only called if the value provided is not an instance of the class or one of its subclasses. The converter
option accepts a symbol that specifies a class method on the object class or a proc. Both will be passed the value and any errors thrown inside the converter will cause the value to be considered invalid. Any returned value that is not the correct class will also be treated as invalid. Any default
that is not an instance of the class or subclass and is not nil
will also be converted.
class ObjectInteraction < ActiveInteraction::Base
object :ip_address,
class: IPAddr,
converter: :new
def execute
ip_address
end
end
ObjectInteraction.run!(ip_address: '192.168.1.1')
# #<IPAddr: IPv4:192.168.1.1/255.255.255.255>
ObjectInteraction.run!(ip_address: 1)
# ActiveInteraction::InvalidInteractionError: Ip address is not a valid object
Record filters allow you to require an instance of a particular class (or one of its subclasses) or a value that can be used to locate an instance of the object. If the value does not match, it will call find
on the class of the record. This is particularly useful when working with ActiveRecord objects. Like an object filter, the class is derived from the name passed but can be specified with the class
option. Any default
that is not an instance of the class or subclass and is not nil
will also be found. Blank strings passed in will be treated as nil
.
class RecordInteraction < ActiveInteraction::Base
record :encoding
def execute
encoding
end
end
> RecordInteraction.run!(encoding: Encoding::US_ASCII)
=> #<Encoding:US-ASCII>
> RecordInteraction.run!(encoding: 'ascii')
=> #<Encoding:US-ASCII>
A different method can be specified by providing a symbol to the finder
option.
ActiveInteraction plays nicely with Rails. You can use interactions to handle your business logic instead of models or controllers. To see how it all works, let's take a look at a complete example of a controller with the typical resourceful actions.
We recommend putting your interactions in app/interactions
. It's also very helpful to group them by model. That way you can look in app/interactions/accounts
for all the ways you can interact with accounts.
- app/
- controllers/
- accounts_controller.rb
- interactions/
- accounts/
- create_account.rb
- destroy_account.rb
- find_account.rb
- list_accounts.rb
- update_account.rb
- models/
- account.rb
- views/
- account/
- edit.html.erb
- index.html.erb
- new.html.erb
- show.html.erb
# GET /accounts
def index
@accounts = ListAccounts.run!
end
Since we're not passing any inputs to ListAccounts
, it makes sense to use .run!
instead of .run
. If it failed, that would mean we probably messed up writing the interaction.
class ListAccounts < ActiveInteraction::Base
def execute
Account.not_deleted.order(last_name: :asc, first_name: :asc)
end
end
Up next is the show action. For this one we'll define a helper method to handle raising the correct errors. We have to do this because calling .run!
would raise an ActiveInteraction::InvalidInteractionError
instead of an ActiveRecord::RecordNotFound
. That means Rails would render a 500 instead of a 404.
# GET /accounts/:id
def show
@account = find_account!
end
private
def find_account!
outcome = FindAccount.run(params)
if outcome.valid?
outcome.result
else
fail ActiveRecord::RecordNotFound, outcome.errors.full_messages.to_sentence
end
end
This probably looks a little different than you're used to. Rails commonly handles this with a before_filter
that sets the @account
instance variable. Why is all this interaction code better? Two reasons: One, you can reuse the FindAccount
interaction in other places, like your API controller or a Resque task. And two, if you want to change how accounts are found, you only have to change one place.
Inside the interaction, we could use #find
instead of #find_by_id
. That way we wouldn't need the #find_account!
helper method in the controller because the error would bubble all the way up. However, you should try to avoid raising errors from interactions. If you do, you'll have to deal with raised exceptions as well as the validity of the outcome.
class FindAccount < ActiveInteraction::Base
integer :id
def execute
account = Account.not_deleted.find_by_id(id)
if account
account
else
errors.add(:id, 'does not exist')
end
end
end
Note that it's perfectly fine to add errors during execution. Not all errors have to come from checking or validation.
The new action will be a little different than the ones we've looked at so far. Instead of calling .run
or .run!
, it's going to initialize a new interaction. This is possible because interactions behave like ActiveModels.
# GET /accounts/new
def new
@account = CreateAccount.new
end
Since interactions behave like ActiveModels, we can use ActiveModel validations with them. We'll use validations here to make sure that the first and last names are not blank. The validations section goes into more detail about this.
class CreateAccount < ActiveInteraction::Base
string :first_name, :last_name
validates :first_name, :last_name,
presence: true
def to_model
Account.new
end
def execute
account = Account.new(inputs)
unless account.save
errors.merge!(account.errors)
end
account
end
end
We used a couple of advanced features here. The #to_model
method helps determine the correct form to use in the view. Check out the section on forms for more about that. Inside #execute
, we merge errors. This is a convenient way to move errors from one object to another. Read more about it in the errors section.
The create action has a lot in common with the new action. Both of them use the CreateAccount
interaction. And if creating the account fails, this action falls back to rendering the new action.
# POST /accounts
def create
outcome = CreateAccount.run(params.fetch(:account, {}))
if outcome.valid?
redirect_to(outcome.result)
else
@account = outcome
render(:new)
end
end
Note that we have to pass a hash to .run
. Passing nil
is an error.
Since we're using an interaction, we don't need strong parameters. The interaction will ignore any inputs that weren't defined by filters. So you can forget about params.require
and params.permit
because interactions handle that for you.
The destroy action will reuse the #find_account!
helper method we wrote earlier.
# DELETE /accounts/:id
def destroy
DestroyAccount.run!(account: find_account!)
redirect_to(accounts_url)
end
In this simple example, the destroy interaction doesn't do much. It's not clear that you gain anything by putting it in an interaction. But in the future, when you need to do more than account.destroy
, you'll only have to update one spot.
class DestroyAccount < ActiveInteraction::Base
object :account
def execute
account.destroy
end
end
Just like the destroy action, editing uses the #find_account!
helper. Then it creates a new interaction instance to use as a form object.
# GET /accounts/:id/edit
def edit
account = find_account!
@account = UpdateAccount.new(
account: account,
first_name: account.first_name,
last_name: account.last_name)
end
The interaction that updates accounts is more complicated than the others. It requires an account to update, but the other inputs are optional. If they're missing, it'll ignore those attributes. If they're present, it'll update them.
class UpdateAccount < ActiveInteraction::Base
object :account
string :first_name, :last_name,
default: nil
validates :first_name,
presence: true,
unless: -> { first_name.nil? }
validates :last_name,
presence: true,
unless: -> { last_name.nil? }
def execute
account.first_name = first_name if first_name.present?
account.last_name = last_name if last_name.present?
unless account.save
errors.merge!(account.errors)
end
account
end
end
Hopefully you've gotten the hang of this by now. We'll use #find_account!
to get the account. Then we'll build up the inputs for UpdateAccount
. Then we'll run the interaction and either redirect to the updated account or back to the edit page.
# PUT /accounts/:id
def update
inputs = { account: find_account! }.reverse_merge(params[:account])
outcome = UpdateAccount.run(inputs)
if outcome.valid?
redirect_to(outcome.result)
else
@account = outcome
render(:edit)
end
end
ActiveSupport::Callbacks provides a powerful framework for defining callbacks. ActiveInteraction uses that framework to allow hooking into various parts of an interaction's lifecycle.
class Increment < ActiveInteraction::Base
set_callback :filter, :before, -> { puts 'before filter' }
integer :x
set_callback :validate, :after, -> { puts 'after validate' }
validates :x,
numericality: { greater_than_or_equal_to: 0 }
set_callback :execute, :around, lambda { |_interaction, block|
puts '>>>'
block.call
puts '<<<'
}
def execute
puts 'executing'
x + 1
end
end
Increment.run!(x: 1)
# before filter
# after validate
# >>>
# executing
# <<<
# => 2
In order, the available callbacks are filter
, validate
, and execute
. You can set before
, after
, or around
on any of them.
You can run interactions from within other interactions with #compose
. If the interaction is successful, it'll return the result (just like if you had called it with .run!
). If something went wrong, execution will halt immediately and the errors will be moved onto the caller.
class Add < ActiveInteraction::Base
integer :x, :y
def execute
x + y
end
end
class AddThree < ActiveInteraction::Base
integer :x
def execute
compose(Add, x: x, y: 3)
end
end
AddThree.run!(x: 5)
# => 8
To bring in filters from another interaction, use .import_filters
. Combined with inputs
, delegating to another interaction is a piece of cake.
class AddAndDouble < ActiveInteraction::Base
import_filters Add
def execute
compose(Add, inputs) * 2
end
end
Note that errors in composed interactions have a few tricky cases. See the errors section for more information about them.
The default value for an input can take on many different forms. Setting the default to nil
makes the input optional. Setting it to some value makes that the default value for that input. Setting it to a lambda will lazily set the default value for that input. That means the value will be computed when the interaction is run, as opposed to when it is defined.
Lambda defaults are evaluated in the context of the interaction, so you can use the values of other inputs in them.
# This input is optional.
time :a, default: nil
# This input defaults to `Time.at(123)`.
time :b, default: Time.at(123)
# This input lazily defaults to `Time.now`.
time :c, default: -> { Time.now }
# This input defaults to the value of `c` plus 10 seconds.
time :d, default: -> { c + 10 }
Use the desc
option to provide human-readable descriptions of filters. You should prefer these to comments because they can be used to generate documentation. The interaction class has a .filters
method that returns a hash of filters. Each filter has a #desc
method that returns the description.
class Descriptive < ActiveInteraction::Base
string :first_name,
desc: 'your first name'
string :last_name,
desc: 'your last name'
end
Descriptive.filters.each do |name, filter|
puts "#{name}: #{filter.desc}"
end
# first_name: your first name
# last_name: your last name
ActiveInteraction provides detailed errors for easier introspection and testing of errors. Detailed errors improve on regular errors by adding a symbol that represents the type of error that has occurred. Let's look at an example where an item is purchased using a credit card.
class BuyItem < ActiveInteraction::Base
object :credit_card, :item
hash :options do
boolean :gift_wrapped
end
def execute
order = credit_card.purchase(item)
notify(credit_card.account)
order
end
private def notify(account)
# ...
end
end
Having missing or invalid inputs causes the interaction to fail and return errors.
outcome = BuyItem.run(item: 'Thing', options: { gift_wrapped: 'yes' })
outcome.errors.messages
# => {:credit_card=>["is required"], :item=>["is not a valid object"], :"options.gift_wrapped"=>["is not a valid boolean"]}
Determining the type of error based on the string is difficult if not impossible. Calling #details
instead of #messages
on errors
gives you the same list of errors with a testable label representing the error.
outcome.errors.details
# => {:credit_card=>[{:error=>:missing}], :item=>[{:error=>:invalid_type, :type=>"object"}], :"options.gift_wrapped"=>[{:error=>:invalid_type, :type=>"boolean"}]}
Detailed errors can also be manually added during the execute call by passing a symbol to #add
instead of a string.
def execute
errors.add(:monster, :no_passage)
end
ActiveInteraction also supports merging errors. This is useful if you want to delegate validation to some other object. For example, if you have an interaction that updates a record, you might want that record to validate itself. By using the #merge!
helper on errors
, you can do exactly that.
class UpdateThing < ActiveInteraction::Base
object :thing
def execute
unless thing.save
errors.merge!(thing.errors)
end
thing
end
end
When a composed interaction fails, its errors are merged onto the caller. This generally produces good error messages, but there are a few cases to look out for.
class Inner < ActiveInteraction::Base
boolean :x, :y
end
class Outer < ActiveInteraction::Base
string :x
boolean :z, default: nil
def execute
compose(Inner, x: x, y: z)
end
end
outcome = Outer.run(x: 'yes')
outcome.errors.details
# => { :x => [{ :error => :invalid_type, :type => "boolean" }],
# :base => [{ :error => "Y is required" }] }
outcome.errors.full_messages.join(' and ')
# => "X is not a valid boolean and Y is required"
Since both interactions have an input called x
, the inner error for that input is moved to the x
error on the outer interaction. This results in a misleading error that claims the input x
is not a valid boolean even though it's a string on the outer interaction.
Since only the inner interaction has an input called y
, the inner error for that input is moved to the base
error on the outer interaction. This results in a confusing error that claims the input y
is required even though it's not present on the outer interaction.
The outcome returned by .run
can be used in forms as though it were an ActiveModel object. You can also create a form object by calling .new
on the interaction.
Given an application with an Account
model we'll create a new Account
using the CreateAccount
interaction.
# GET /accounts/new
def new
@account = CreateAccount.new
end
# POST /accounts
def create
outcome = CreateAccount.run(params.fetch(:account, {}))
if outcome.valid?
redirect_to(outcome.result)
else
@account = outcome
render(:new)
end
end
The form used to create a new Account
has slightly more information on the form_for
call than you might expect.
<%= form_for @account, as: :account, url: accounts_path do |f| %>
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= f.submit 'Create' %>
<% end %>
This is necessary because we want the form to act like it is creating a new Account
. Defining to_model
on the CreateAccount
interaction tells the form to treat our interaction like an Account
.
class CreateAccount < ActiveInteraction::Base
# ...
def to_model
Account.new
end
end
Now our form_for
call knows how to generate the correct URL and param name (i.e. params[:account]
).
# app/views/accounts/new.html.erb
<%= form_for @account do |f| %>
<%# ... %>
<% end %>
If you have an interaction that updates an Account
, you can define to_model
to return the object you're updating.
class UpdateAccount < ActiveInteraction::Base
# ...
object :account
def to_model
account
end
end
ActiveInteraction also supports formtastic and simple_form. The filters used to define the inputs on your interaction will relay type information to these gems. As a result, form fields will automatically use the appropriate input type.
It can be convenient to apply the same options to a bunch of inputs. One common use case is making many inputs optional. Instead of setting default: nil
on each one of them, you can use with_options
to reduce duplication.
with_options default: nil do
date :birthday
string :name
boolean :wants_cake
end
Optional inputs can be defined by using the :default
option as described in the filters section. Within the interaction, provided and default values are merged to create inputs
. There are times where it is useful to know whether a value was passed to run
or the result of a filter default. In particular, it is useful when nil
is an acceptable value. For example, you may optionally track your users' birthdays. You can use the inputs.given?
predicate to see if an input was even passed to run
. With inputs.given?
you can also check the input of a hash or array filter by passing a series of keys or indexes to check.
class UpdateUser < ActiveInteraction::Base
object :user
date :birthday,
default: nil
def execute
user.birthday = birthday if inputs.given?(:birthday)
errors.merge!(user.errors) unless user.save
user
end
end
Now you have a few options. If you don't want to update their birthday, leave it out of the hash. If you want to remove their birthday, set birthday: nil
. And if you want to update it, pass in the new value as usual.
user = User.find(...)
# Don't update their birthday.
UpdateUser.run!(user: user)
# Remove their birthday.
UpdateUser.run!(user: user, birthday: nil)
# Update their birthday.
UpdateUser.run!(user: user, birthday: Date.new(2000, 1, 2))
ActiveInteraction is i18n aware out of the box! All you have to do is add translations to your project. In Rails, these typically go into config/locales
. For example, let's say that for some reason you want to print everything out backwards. Simply add translations for ActiveInteraction to your hsilgne
locale.
# config/locales/hsilgne.yml
hsilgne:
active_interaction:
types:
array: yarra
boolean: naeloob
date: etad
date_time: emit etad
decimal: lamiced
file: elif
float: taolf
hash: hsah
integer: regetni
interface: ecafretni
object: tcejbo
string: gnirts
symbol: lobmys
time: emit
errors:
messages:
invalid: dilavni si
invalid_type: '%{type} dilav a ton si'
missing: deriuqer si
Then set your locale and run interactions like normal.
class I18nInteraction < ActiveInteraction::Base
string :name
end
I18nInteraction.run(name: false).errors.messages[:name]
# => ["is not a valid string"]
I18n.locale = :hsilgne
I18nInteraction.run(name: false).errors.messages[:name]
# => ["gnirts dilav a ton si"]
Everything else works like an activerecord
entry. For example, to rename an attribute you can use attributes
.
Here we'll rename the num
attribute on an interaction named product
:
en:
active_interaction:
attributes:
product:
num: 'Number'
ActiveInteraction is brought to you by Aaron Lasseigne. Along with Aaron, Taylor Fausak helped create and maintain ActiveInteraction but has since moved on.
If you want to contribute to ActiveInteraction, please read our contribution guidelines. A complete list of contributors is available on GitHub.
ActiveInteraction is licensed under the MIT License.
Author: AaronLasseigne
Source code: https://github.com/AaronLasseigne/active_interaction
License: MIT license
1659511140
:warning: | This gem is now in [passive maintenance mode][passive]. [(more)][passive] |
Making HTML emails comfortable for the Ruby rockstars
Roadie tries to make sending HTML emails a little less painful by inlining stylesheets and rewriting relative URLs for you inside your emails.
Email clients have bad support for stylesheets, and some of them blocks stylesheets from downloading. The easiest way to handle this is to work with inline styles (style="..."
), but that is error prone and hard to work with as you cannot use classes and/or reuse styling over your HTML.
This gem makes this easier by automatically inlining stylesheets into the document. You give Roadie your CSS, or let it find it by itself from the <link>
and <style>
tags in the markup, and it will go through all of the selectors assigning the styles to the matching elements. Careful attention has been put into selectors being applied in the correct order, so it should behave just like in the browser.
"Dynamic" selectors (:hover
, :visited
, :focus
, etc.), or selectors not understood by Nokogiri will be inlined into a single <style>
element for those email clients that support it. This changes specificity a great deal for these rules, so it might not work 100% out of the box. (See more about this below)
Roadie also rewrites all relative URLs in the email to an absolute counterpart, making images you insert and those referenced in your stylesheets work. No more headaches about how to write the stylesheets while still having them work with emails from your acceptance environments. You can disable this on specific elements using a data-roadie-ignore
marker.
!important
styles.style
attribute of tags.:hover
, @media { ... }
and friends around in a separate <style>
element.href
s and img
src
s absolute.data-roadie-ignore
markers before finishing the HTML.Add this gem to your Gemfile as recommended by Rubygems and run bundle install
.
gem 'roadie', '~> 4.0'
Your document instance can be configured with several options:
url_options
- Dictates how absolute URLs should be built.keep_uninlinable_css
- Set to false to skip CSS that cannot be inlined.merge_media_queries
- Set to false to not group media queries. Some users might prefer to not group rules within media queries because it will result in rules getting reordered. e.g.@media(max-width: 600px) { .col-6 { display: block; } }
@media(max-width: 400px) { .col-12 { display: inline-block; } }
@media(max-width: 600px) { .col-12 { display: block; } }
@media(max-width: 600px) { .col-6 { display: block; } .col-12 { display: block; } }
@media(max-width: 400px) { .col-12 { display: inline-block; } }
asset_providers
- A list of asset providers that are invoked when CSS files are referenced. See below.external_asset_providers
- A list of asset providers that are invoked when absolute CSS URLs are referenced. See below.before_transformation
- A callback run before transformation starts.after_transformation
- A callback run after transformation is completed.In order to make URLs absolute you need to first configure the URL options of the document.
html = '... <a href="/about-us">Read more!</a> ...'
document = Roadie::Document.new html
document.url_options = {host: "myapp.com", protocol: "https"}
document.transform
# => "... <a href=\"https://myapp.com/about-us\">Read more!</a> ..."
The following URLs will be rewritten for you:
a[href]
(HTML)img[src]
(HTML)url()
(CSS)You can disable individual elements by adding an data-roadie-ignore
marker on them. CSS will still be inlined on those elements, but URLs will not be rewritten.
<a href="|UNSUBSCRIBE_URL|" data-roadie-ignore>Unsubscribe</a>
By default, style
and link
elements in the email document's head
are processed along with the stylesheets and removed from the head
.
You can set a special data-roadie-ignore
attribute on style
and link
tags that you want to ignore (the attribute will be removed, however). This is the place to put things like :hover
selectors that you want to have for email clients allowing them.
Style and link elements with media="print"
are also ignored.
<head>
<link rel="stylesheet" type="text/css" href="/assets/emails/rock.css"> <!-- Will be inlined with normal providers -->
<link rel="stylesheet" type="text/css" href="http://www.metal.org/metal.css"> <!-- Will be inlined with external providers, *IF* specified; otherwise ignored. -->
<link rel="stylesheet" type="text/css" href="/assets/jazz.css" media="print"> <!-- Will NOT be inlined; print style -->
<link rel="stylesheet" type="text/css" href="/ambient.css" data-roadie-ignore> <!-- Will NOT be inlined; ignored -->
<style></style> <!-- Will be inlined -->
<style data-roadie-ignore></style> <!-- Will NOT be inlined; ignored -->
</head>
Roadie will use the given asset providers to look for the actual CSS that is referenced. If you don't change the default, it will use the Roadie::FilesystemProvider
which looks for stylesheets on the filesystem, relative to the current working directory.
Example:
# /home/user/foo/stylesheets/primary.css
body { color: green; }
# /home/user/foo/script.rb
html = <<-HTML
<html>
<head>
<link rel="stylesheet" type="text/css" href="/stylesheets/primary.css">
</head>
<body>
</body>
</html>
HTML
Dir.pwd # => "/home/user/foo"
document = Roadie::Document.new html
document.transform # =>
# <!DOCTYPE html>
# <html>
# <head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></head>
# <body style="color:green;"></body>
# </html>
If a referenced stylesheet cannot be found, the #transform
method will raise an Roadie::CssNotFound
error. If you instead want to ignore missing stylesheets, you can use the NullProvider
.
You can write your own providers if you need very specific behavior for your app, or you can use the built-in providers. Providers come in two groups: normal and external. Normal providers handle paths without host information (/style/foo.css
) while external providers handle URLs with host information (//example.com/foo.css
, localhost:3001/bar.css
, and so on).
The default configuration is to not have any external providers configured, which will cause those referenced stylesheets to be ignored. Adding one or more providers for external assets causes all of them to be searched and inlined, so if you only want this to happen to specific stylesheets you need to add ignore markers to every other styleshheet (see above).
Included providers:
FilesystemProvider
– Looks for files on the filesystem, relative to the given directory unless otherwise specified.ProviderList
– Wraps a list of other providers and searches them in order. The asset_providers
setting is an instance of this. It behaves a lot like an array, so you can push, pop, shift and unshift to it.NullProvider
– Does not actually provide anything, it always finds empty stylesheets. Use this in tests or if you want to ignore stylesheets that cannot be found by your other providers (or if you want to force the other providers to never run).NetHttpProvider
– Downloads stylesheets using Net::HTTP
. Can be given a whitelist of hosts to download from.CachedProvider
– Wraps another provider (or ProviderList
) and caches responses inside the provided cache store.PathRewriterProvider
– Rewrites the passed path and then passes it on to another provider (or ProviderList
).If you want to search several locations on the filesystem, you can declare that:
document.asset_providers = [
Roadie::FilesystemProvider.new(App.root.join("resources", "stylesheets")),
Roadie::FilesystemProvider.new(App.root.join("system", "uploads", "stylesheets")),
]
NullProvider
If you want to ignore stylesheets that cannot be found instead of crashing, push the NullProvider
to the end:
# Don't crash on missing assets
document.asset_providers << Roadie::NullProvider.new
# Don't download assets in tests
document.external_asset_providers.unshift Roadie::NullProvider.new
Note: This will cause the referenced stylesheet to be removed from the source code, so email client will never see it either.
NetHttpProvider
The NetHttpProvider
will download the URLs that is is given using Ruby's standard Net::HTTP
library.
You can give it a whitelist of hosts that downloads are allowed from:
document.external_asset_providers << Roadie::NetHttpProvider.new(
whitelist: ["myapp.com", "assets.myapp.com", "cdn.cdnnetwork.co.jp"],
)
document.external_asset_providers << Roadie::NetHttpProvider.new # Allows every host
CachedProvider
You might want to cache providers from working several times. If you are sending several emails quickly from the same process, this might also save a lot of time on parsing the stylesheets if you use in-memory storage such as a hash.
You can wrap any other kind of providers with it, even a ProviderList
:
document.external_asset_providers = Roadie::CachedProvider.new(document.external_asset_providers, my_cache)
If you don't pass a cache backend, it will use a normal Hash
. The cache store must follow this protocol:
my_cache["key"] = some_stylesheet_instance # => #<Roadie::Stylesheet instance>
my_cache["key"] # => #<Roadie::Stylesheet instance>
my_cache["missing"] # => nil
Warning: The default Hash
store will never be cleared, so make sure you don't allow the number of unique asset paths to grow too large in a single run. This is especially important if you run Roadie in a daemon that accepts arbritary documents, and/or if you use hash digests in your filenames. Making a new instance of CachedProvider
will use a new Hash
instance.
You can implement your own custom cache store by implementing the []
and []=
methods.
class MyRoadieMemcacheStore
def initialize(memcache)
@memcache = memcache
end
def [](path)
css = memcache.read("assets/#{path}/css")
if css
name = memcache.read("assets/#{path}/name") || "cached #{path}"
Roadie::Stylesheet.new(name, css)
end
end
def []=(path, stylesheet)
memcache.write("assets/#{path}/css", stylesheet.to_s)
memcache.write("assets/#{path}/name", stylesheet.name)
stylesheet # You need to return the set Stylesheet
end
end
document.external_asset_providers = Roadie::CachedProvider.new(
document.external_asset_providers,
MyRoadieMemcacheStore.new(MemcacheClient.instance)
)
If you are using Rspec, you can test your implementation by using the shared examples for the "roadie cache store" role:
require "roadie/rspec"
describe MyRoadieMemcacheStore do
let(:memcache_client) { MemcacheClient.instance }
subject { MyRoadieMemcacheStore.new(memcache_client) }
it_behaves_like "roadie cache store" do
before { memcache_client.clear }
end
end
PathRewriterProvider
With this provider, you can rewrite the paths that are searched in order to more easily support another provider. Examples could include rewriting absolute URLs into something that can be found on the filesystem, or to access internal hosts instead of external ones.
filesystem = Roadie::FilesystemProvider.new("assets")
document.asset_providers << Roadie::PathRewriterProvider.new(filesystem) do |path|
path.sub('stylesheets', 'css').downcase
end
document.external_asset_providers = Roadie::PathRewriterProvider.new(filesystem) do |url|
if url =~ /myapp\.com/
URI.parse(url).path.sub(%r{^/assets}, '')
else
url
end
end
You can also wrap a list, for example to implement external_asset_providers
by composing the normal asset_providers
:
document.external_asset_providers =
Roadie::PathRewriterProvider.new(document.asset_providers) do |url|
URI.parse(url).path
end
Writing your own provider is also easy. You need to provide:
#find_stylesheet(name)
, returning either a Roadie::Stylesheet
or nil
.#find_stylesheet!(name)
, returning either a Roadie::Stylesheet
or raising Roadie::CssNotFound
.class UserAssetsProvider
def initialize(user_collection)
@user_collection = user_collection
end
def find_stylesheet(name)
if name =~ %r{^/users/(\d+)\.css$}
user = @user_collection.find_user($1)
Roadie::Stylesheet.new("user #{user.id} stylesheet", user.stylesheet)
end
end
def find_stylesheet!(name)
find_stylesheet(name) or
raise Roadie::CssNotFound.new(
css_name: name, message: "does not match a user stylesheet", provider: self
)
end
# Instead of implementing #find_stylesheet!, you could also:
# include Roadie::AssetProvider
# That will give you a default implementation without any error message. If
# you have multiple error cases, it's recommended that you implement
# #find_stylesheet! without #find_stylesheet and raise with an explanatory
# error message.
end
# Try to look for a user stylesheet first, then fall back to normal filesystem lookup.
document.asset_providers = [
UserAssetsProvider.new(app),
Roadie::FilesystemProvider.new('./stylesheets'),
]
You can test for compliance by using the built-in RSpec examples:
require 'spec_helper'
require 'roadie/rspec'
describe MyOwnProvider do
# Will use the default `subject` (MyOwnProvider.new)
it_behaves_like "roadie asset provider", valid_name: "found.css", invalid_name: "does_not_exist.css"
# Extra setup just for these tests:
it_behaves_like "roadie asset provider", valid_name: "found.css", invalid_name: "does_not_exist.css" do
subject { MyOwnProvider.new(...) }
before { stub_dependencies }
end
end
Some CSS is impossible to inline properly. :hover
and ::after
comes to mind. Roadie tries its best to keep these around by injecting them inside a new <style>
element in the <head>
(or at the beginning of the partial if transforming a partial document).
The problem here is that Roadie cannot possible adjust the specificity for you, so they will not apply the same way as they did before the styles were inlined.
Another caveat is that a lot of email clients does not support this (which is the entire point of inlining in the first place), so don't put anything important in here. Always handle the case of these selectors not being part of the email.
Inlined styles will have much higher specificity than styles in a <style>
. Here's an example:
<style>p:hover { color: blue; }</style>
<p style="color: green;">Hello world</p>
When hovering over this <p>
, the color will not change as the color: green
rule takes precedence. You can get it to work by adding !important
to the :hover
rule.
It would be foolish to try to automatically inject !important
on every rule automatically, so this is a manual process.
If you'd rather skip this and have the styles not possible to inline disappear, you can turn off this feature by setting the keep_uninlinable_css
option to false.
document.keep_uninlinable_css = false
Callbacks allow you to do custom work on documents before they are transformed. The Nokogiri document tree is passed to the callable along with the Roadie::Document
instance:
class TrackNewsletterLinks
def call(dom, document)
dom.css("a").each { |link| fix_link(link) }
end
def fix_link(link)
divider = (link['href'] =~ /?/ ? '&' : '?')
link['href'] = link['href'] + divider + 'source=newsletter'
end
end
document.before_transformation = ->(dom, document) {
logger.debug "Inlining document with title #{dom.at_css('head > title').try(:text)}"
}
document.after_transformation = TrackNewsletterLinks.new
You can configure the underlying HTML/XML engine to output XHTML or HTML (which is the default). One usecase for this is that {
tokens usually gets escaped to {
, which would be a problem if you then pass the resulting HTML on to some other templating engine that uses those tokens (like Handlebars or Mustache).
document.mode = :xhtml
This will also affect the emitted <!DOCTYPE>
if transforming a full document. Partial documents does not have a <!DOCTYPE>
.
Tested with Github CI using:
Let me know if you want any other runtime supported officially.
This project follows Semantic Versioning and has been since version 1.0.0.
Roadie uses Nokogiri to parse and regenerate the HTML of your email, which means that some unintentional changes might show up.
One example would be that Nokogiri might remove your
s in some cases.
Another example is Nokogiri's lack of HTML5 support, so certain new element might have spaces removed. I recommend you don't use HTML5 in emails anyway because of bad email client support (that includes web mail!).
Roadie uses Nokogiri to parse the HTML of your email, so any C-like problems like segfaults are likely in that end. The best way to fix this is to first upgrade libxml2 on your system and then reinstall Nokogiri. Instructions on how to do this on most platforms, see Nokogiri's official install guide.
@keyframes
?The CSS Parser used in Roadie does not handle keyframes. I don't think any email clients do either, but if you want to keep on trying you can add them manually to a <style>
element (or a separate referenced stylesheet) and tell Roadie not to touch them.
@media
queries are reordered, how can I fix this?Different @media
query blocks with the same conditions are merged by default, which will change the order in some cases. You can disable this by setting merge_media_queries
to false
. (See Install & Usage section above).
<body>
elements that are added?It sounds like you want to transform a partial document. Maybe you are building partials or template fragments to later place in other documents. Use Document#transform_partial
instead of Document#transform
in order to treat the HTML as a partial document.
If you add the data-roadie-ignore
attribute on an element, URL rewriting will not be performed on that element. This could be really useful for you if you intend to send the email through some other rendering pipeline that replaces some placeholders/variables.
<a href="/about-us">About us</a>
<a href="|UNSUBSCRIBE_URL|" data-roadie-ignore>Unsubscribe</a>
Note that this will not skip CSS inlining on the element; it will still get the correct styles applied.
If the URL is invalid on purpose, see Can I skip URL rewriting on a specific element? above. Otherwise, you can try to parse it yourself using Ruby's URI
class and see if you can figure it out.
require "uri"
URI.parse("https://example.com/best image.jpg") # raises
URI.parse("https://example.com/best%20image.jpg") # Works!
bundle install
rake
Roadie is set up with the assumption that all CSS and HTML passing through it is under your control. It is not recommended to run arbritary HTML with the default settings.
Care has been given to try to secure all file system accesses, but it is never guaranteed that someone cannot access something they should not be able to access.
In order to secure Roadie against file system access, only use your own asset providers that you yourself can secure against your particular environment.
If you have found any security vulnerability, please email me at magnus.bergmark+security@gmail.com
to disclose it. For very sensitive issues, please use my public GPG key. You can also encrypt your message with my public key and open an issue if you do not want to email me directly. Thank you.
This gem was previously tied to Rails. It is now framework-agnostic and supports any type of HTML documents. If you want to use it with Rails, check out roadie-rails.
Major contributors to Roadie:
You can see all contributors on GitHub.
(The MIT License)
Copyright (c) 2009-2022 Magnus Bergmark, Jim Neath / Purify, and contributors.
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ‘Software’), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED ‘AS IS’, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Author: Mange
Source code: https://github.com/Mange/roadie
License: MIT license
1658734620
Provides Chromium network errors found in net_error_list.h as custom error classes that can be conveniently used in Node.js, Electron apps and browsers.
The errors correspond to the error codes that are provided in Electron's did-fail-load
events of the WebContents class and the webview tag.
import
and export
, and a CommonJS build. Your bundler can use the ES6 modules if it supports the "module"
or "jsnext:main"
directives in the package.json.npm install chromium-net-errors --save
import * as chromiumNetErrors from 'chromium-net-errors';
// or
const chromiumNetErrors = require('chromium-net-errors');
import { app, BrowserWindow } from 'electron';
import * as chromiumNetErrors from 'chromium-net-errors';
app.on('ready', () => {
const win = new BrowserWindow({
width: 800,
height: 600,
});
win.webContents.on('did-fail-load', (event) => {
try {
const Err = chromiumNetErrors.getErrorByCode(event.errorCode);
throw new Err();
} catch (err) {
if (err instanceof chromiumNetErrors.NameNotResolvedError) {
console.error(`The name '${event.validatedURL}' could not be resolved:\n ${err.message}`);
} else {
console.error(`Something went wrong while loading ${event.validatedURL}`);
}
}
});
win.loadURL('http://blablanotexist.com');
});
import * as chromiumNetErrors from 'chromium-net-errors';
const err = new chromiumNetErrors.ConnectionTimedOutError();
console.log(err instanceof Error);
// true
console.log(err instanceof chromiumNetErrors.ChromiumNetError);
// true
console.log(err instanceof chromiumNetErrors.ConnectionTimedOutError);
// true
function thrower() {
throw new chromiumNetErrors.ConnectionTimedOutError();
}
try {
thrower();
} catch (err) {
console.log(err instanceof Error);
// true
console.log(err instanceof chromiumNetErrors.ChromiumNetError);
// true
console.log(err instanceof chromiumNetErrors.ConnectionTimedOutError);
// true
}
Get the class of an error by its errorCode
.
const Err = chromiumNetErrors.getErrorByCode(-201);
const err = new Err();
console.log(err instanceof chromiumNetErrors.CertDateInvalidError);
// true
console.log(err.isCertificateError());
// true
console.log(err.type);
// 'certificate'
console.log(err.message);
// The server responded with a certificate that, by our clock, appears to
// either not yet be valid or to have expired. This could mean:
//
// 1. An attacker is presenting an old certificate for which they have
// managed to obtain the private key.
//
// 2. The server is misconfigured and is not presenting a valid cert.
//
// 3. Our clock is wrong.
Get the class of an error by its errorDescription
.
const Err = chromiumNetErrors.getErrorByDescription('CERT_DATE_INVALID');
const err = new Err();
console.log(err instanceof chromiumNetErrors.CertDateInvalidError);
// true
console.log(err.isCertificateError());
// true
console.log(err.type);
// 'certificate'
console.log(err.message);
// The server responded with a certificate that, by our clock, appears to
// either not yet be valid or to have expired. This could mean:
//
// 1. An attacker is presenting an old certificate for which they have
// managed to obtain the private key.
//
// 2. The server is misconfigured and is not presenting a valid cert.
//
// 3. Our clock is wrong.
Get an array of all possible errors.
console.log(chromiumNetErrors.getErrors());
// [ { name: 'IoPendingError',
// code: -1,
// description: 'IO_PENDING',
// type: 'system',
// message: 'An asynchronous IO operation is not yet complete. This usually does not\nindicate a fatal error. Typically this error will be generated as a\nnotification to wait for some external notification that the IO operation\nfinally completed.' },
// { name: 'FailedError',
// code: -2,
// description: 'FAILED',
// type: 'system',
// message: 'A generic failure occurred.' },
// { name: 'AbortedError',
// code: -3,
// description: 'ABORTED',
// type: 'system',
// message: 'An operation was aborted (due to user action).' },
// { name: 'InvalidArgumentError',
// code: -4,
// description: 'INVALID_ARGUMENT',
// type: 'system',
// message: 'An argument to the function is incorrect.' },
// { name: 'InvalidHandleError',
// code: -5,
// description: 'INVALID_HANDLE',
// type: 'system',
// message: 'The handle or file descriptor is invalid.' },
// ...
// ]
An asynchronous IO operation is not yet complete. This usually does not indicate a fatal error. Typically this error will be generated as a notification to wait for some external notification that the IO operation finally completed.
IoPendingError
-1
IO_PENDING
const err = new chromiumNetErrors.IoPendingError();
// or
const Err = chromiumNetErrors.getErrorByCode(-1);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('IO_PENDING');
const err = new Err();
A generic failure occurred.
FailedError
-2
FAILED
const err = new chromiumNetErrors.FailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-2);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FAILED');
const err = new Err();
An operation was aborted (due to user action).
AbortedError
-3
ABORTED
const err = new chromiumNetErrors.AbortedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-3);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ABORTED');
const err = new Err();
An argument to the function is incorrect.
InvalidArgumentError
-4
INVALID_ARGUMENT
const err = new chromiumNetErrors.InvalidArgumentError();
// or
const Err = chromiumNetErrors.getErrorByCode(-4);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_ARGUMENT');
const err = new Err();
The handle or file descriptor is invalid.
InvalidHandleError
-5
INVALID_HANDLE
const err = new chromiumNetErrors.InvalidHandleError();
// or
const Err = chromiumNetErrors.getErrorByCode(-5);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_HANDLE');
const err = new Err();
The file or directory cannot be found.
FileNotFoundError
-6
FILE_NOT_FOUND
const err = new chromiumNetErrors.FileNotFoundError();
// or
const Err = chromiumNetErrors.getErrorByCode(-6);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FILE_NOT_FOUND');
const err = new Err();
An operation timed out.
TimedOutError
-7
TIMED_OUT
const err = new chromiumNetErrors.TimedOutError();
// or
const Err = chromiumNetErrors.getErrorByCode(-7);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TIMED_OUT');
const err = new Err();
The file is too large.
FileTooBigError
-8
FILE_TOO_BIG
const err = new chromiumNetErrors.FileTooBigError();
// or
const Err = chromiumNetErrors.getErrorByCode(-8);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FILE_TOO_BIG');
const err = new Err();
An unexpected error. This may be caused by a programming mistake or an invalid assumption.
UnexpectedError
-9
UNEXPECTED
const err = new chromiumNetErrors.UnexpectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-9);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNEXPECTED');
const err = new Err();
Permission to access a resource, other than the network, was denied.
AccessDeniedError
-10
ACCESS_DENIED
const err = new chromiumNetErrors.AccessDeniedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-10);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ACCESS_DENIED');
const err = new Err();
The operation failed because of unimplemented functionality.
NotImplementedError
-11
NOT_IMPLEMENTED
const err = new chromiumNetErrors.NotImplementedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-11);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NOT_IMPLEMENTED');
const err = new Err();
There were not enough resources to complete the operation.
InsufficientResourcesError
-12
INSUFFICIENT_RESOURCES
const err = new chromiumNetErrors.InsufficientResourcesError();
// or
const Err = chromiumNetErrors.getErrorByCode(-12);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INSUFFICIENT_RESOURCES');
const err = new Err();
Memory allocation failed.
OutOfMemoryError
-13
OUT_OF_MEMORY
const err = new chromiumNetErrors.OutOfMemoryError();
// or
const Err = chromiumNetErrors.getErrorByCode(-13);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('OUT_OF_MEMORY');
const err = new Err();
The file upload failed because the file's modification time was different from the expectation.
UploadFileChangedError
-14
UPLOAD_FILE_CHANGED
const err = new chromiumNetErrors.UploadFileChangedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-14);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UPLOAD_FILE_CHANGED');
const err = new Err();
The socket is not connected.
SocketNotConnectedError
-15
SOCKET_NOT_CONNECTED
const err = new chromiumNetErrors.SocketNotConnectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-15);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKET_NOT_CONNECTED');
const err = new Err();
The file already exists.
FileExistsError
-16
FILE_EXISTS
const err = new chromiumNetErrors.FileExistsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-16);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FILE_EXISTS');
const err = new Err();
The path or file name is too long.
FilePathTooLongError
-17
FILE_PATH_TOO_LONG
const err = new chromiumNetErrors.FilePathTooLongError();
// or
const Err = chromiumNetErrors.getErrorByCode(-17);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FILE_PATH_TOO_LONG');
const err = new Err();
Not enough room left on the disk.
FileNoSpaceError
-18
FILE_NO_SPACE
const err = new chromiumNetErrors.FileNoSpaceError();
// or
const Err = chromiumNetErrors.getErrorByCode(-18);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FILE_NO_SPACE');
const err = new Err();
The file has a virus.
FileVirusInfectedError
-19
FILE_VIRUS_INFECTED
const err = new chromiumNetErrors.FileVirusInfectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-19);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FILE_VIRUS_INFECTED');
const err = new Err();
The client chose to block the request.
BlockedByClientError
-20
BLOCKED_BY_CLIENT
const err = new chromiumNetErrors.BlockedByClientError();
// or
const Err = chromiumNetErrors.getErrorByCode(-20);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('BLOCKED_BY_CLIENT');
const err = new Err();
The network changed.
NetworkChangedError
-21
NETWORK_CHANGED
const err = new chromiumNetErrors.NetworkChangedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-21);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NETWORK_CHANGED');
const err = new Err();
The request was blocked by the URL block list configured by the domain administrator.
BlockedByAdministratorError
-22
BLOCKED_BY_ADMINISTRATOR
const err = new chromiumNetErrors.BlockedByAdministratorError();
// or
const Err = chromiumNetErrors.getErrorByCode(-22);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('BLOCKED_BY_ADMINISTRATOR');
const err = new Err();
The socket is already connected.
SocketIsConnectedError
-23
SOCKET_IS_CONNECTED
const err = new chromiumNetErrors.SocketIsConnectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-23);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKET_IS_CONNECTED');
const err = new Err();
The request was blocked because the forced reenrollment check is still pending. This error can only occur on ChromeOS. The error can be emitted by code in chrome/browser/policy/policy_helpers.cc.
BlockedEnrollmentCheckPendingError
-24
BLOCKED_ENROLLMENT_CHECK_PENDING
const err = new chromiumNetErrors.BlockedEnrollmentCheckPendingError();
// or
const Err = chromiumNetErrors.getErrorByCode(-24);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('BLOCKED_ENROLLMENT_CHECK_PENDING');
const err = new Err();
The upload failed because the upload stream needed to be re-read, due to a retry or a redirect, but the upload stream doesn't support that operation.
UploadStreamRewindNotSupportedError
-25
UPLOAD_STREAM_REWIND_NOT_SUPPORTED
const err = new chromiumNetErrors.UploadStreamRewindNotSupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-25);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UPLOAD_STREAM_REWIND_NOT_SUPPORTED');
const err = new Err();
The request failed because the URLRequestContext is shutting down, or has been shut down.
ContextShutDownError
-26
CONTEXT_SHUT_DOWN
const err = new chromiumNetErrors.ContextShutDownError();
// or
const Err = chromiumNetErrors.getErrorByCode(-26);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONTEXT_SHUT_DOWN');
const err = new Err();
The request failed because the response was delivered along with requirements which are not met ('X-Frame-Options' and 'Content-Security-Policy' ancestor checks and 'Cross-Origin-Resource-Policy', for instance).
BlockedByResponseError
-27
BLOCKED_BY_RESPONSE
const err = new chromiumNetErrors.BlockedByResponseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-27);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('BLOCKED_BY_RESPONSE');
const err = new Err();
The request was blocked by system policy disallowing some or all cleartext requests. Used for NetworkSecurityPolicy on Android.
CleartextNotPermittedError
-29
CLEARTEXT_NOT_PERMITTED
const err = new chromiumNetErrors.CleartextNotPermittedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-29);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CLEARTEXT_NOT_PERMITTED');
const err = new Err();
The request was blocked by a Content Security Policy
BlockedByCspError
-30
BLOCKED_BY_CSP
const err = new chromiumNetErrors.BlockedByCspError();
// or
const Err = chromiumNetErrors.getErrorByCode(-30);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('BLOCKED_BY_CSP');
const err = new Err();
The request was blocked because of no H/2 or QUIC session.
H2OrQuicRequiredError
-31
H2_OR_QUIC_REQUIRED
const err = new chromiumNetErrors.H2OrQuicRequiredError();
// or
const Err = chromiumNetErrors.getErrorByCode(-31);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('H2_OR_QUIC_REQUIRED');
const err = new Err();
A connection was closed (corresponding to a TCP FIN).
ConnectionClosedError
-100
CONNECTION_CLOSED
const err = new chromiumNetErrors.ConnectionClosedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-100);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONNECTION_CLOSED');
const err = new Err();
A connection was reset (corresponding to a TCP RST).
ConnectionResetError
-101
CONNECTION_RESET
const err = new chromiumNetErrors.ConnectionResetError();
// or
const Err = chromiumNetErrors.getErrorByCode(-101);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONNECTION_RESET');
const err = new Err();
A connection attempt was refused.
ConnectionRefusedError
-102
CONNECTION_REFUSED
const err = new chromiumNetErrors.ConnectionRefusedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-102);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONNECTION_REFUSED');
const err = new Err();
A connection timed out as a result of not receiving an ACK for data sent. This can include a FIN packet that did not get ACK'd.
ConnectionAbortedError
-103
CONNECTION_ABORTED
const err = new chromiumNetErrors.ConnectionAbortedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-103);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONNECTION_ABORTED');
const err = new Err();
A connection attempt failed.
ConnectionFailedError
-104
CONNECTION_FAILED
const err = new chromiumNetErrors.ConnectionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-104);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONNECTION_FAILED');
const err = new Err();
The host name could not be resolved.
NameNotResolvedError
-105
NAME_NOT_RESOLVED
const err = new chromiumNetErrors.NameNotResolvedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-105);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NAME_NOT_RESOLVED');
const err = new Err();
The Internet connection has been lost.
InternetDisconnectedError
-106
INTERNET_DISCONNECTED
const err = new chromiumNetErrors.InternetDisconnectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-106);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INTERNET_DISCONNECTED');
const err = new Err();
An SSL protocol error occurred.
SslProtocolError
-107
SSL_PROTOCOL_ERROR
const err = new chromiumNetErrors.SslProtocolError();
// or
const Err = chromiumNetErrors.getErrorByCode(-107);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_PROTOCOL_ERROR');
const err = new Err();
The IP address or port number is invalid (e.g., cannot connect to the IP address 0 or the port 0).
AddressInvalidError
-108
ADDRESS_INVALID
const err = new chromiumNetErrors.AddressInvalidError();
// or
const Err = chromiumNetErrors.getErrorByCode(-108);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ADDRESS_INVALID');
const err = new Err();
The IP address is unreachable. This usually means that there is no route to the specified host or network.
AddressUnreachableError
-109
ADDRESS_UNREACHABLE
const err = new chromiumNetErrors.AddressUnreachableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-109);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ADDRESS_UNREACHABLE');
const err = new Err();
The server requested a client certificate for SSL client authentication.
SslClientAuthCertNeededError
-110
SSL_CLIENT_AUTH_CERT_NEEDED
const err = new chromiumNetErrors.SslClientAuthCertNeededError();
// or
const Err = chromiumNetErrors.getErrorByCode(-110);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_CLIENT_AUTH_CERT_NEEDED');
const err = new Err();
A tunnel connection through the proxy could not be established.
TunnelConnectionFailedError
-111
TUNNEL_CONNECTION_FAILED
const err = new chromiumNetErrors.TunnelConnectionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-111);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TUNNEL_CONNECTION_FAILED');
const err = new Err();
No SSL protocol versions are enabled.
NoSslVersionsEnabledError
-112
NO_SSL_VERSIONS_ENABLED
const err = new chromiumNetErrors.NoSslVersionsEnabledError();
// or
const Err = chromiumNetErrors.getErrorByCode(-112);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NO_SSL_VERSIONS_ENABLED');
const err = new Err();
The client and server don't support a common SSL protocol version or cipher suite.
SslVersionOrCipherMismatchError
-113
SSL_VERSION_OR_CIPHER_MISMATCH
const err = new chromiumNetErrors.SslVersionOrCipherMismatchError();
// or
const Err = chromiumNetErrors.getErrorByCode(-113);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_VERSION_OR_CIPHER_MISMATCH');
const err = new Err();
The server requested a renegotiation (rehandshake).
SslRenegotiationRequestedError
-114
SSL_RENEGOTIATION_REQUESTED
const err = new chromiumNetErrors.SslRenegotiationRequestedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-114);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_RENEGOTIATION_REQUESTED');
const err = new Err();
The proxy requested authentication (for tunnel establishment) with an unsupported method.
ProxyAuthUnsupportedError
-115
PROXY_AUTH_UNSUPPORTED
const err = new chromiumNetErrors.ProxyAuthUnsupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-115);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PROXY_AUTH_UNSUPPORTED');
const err = new Err();
During SSL renegotiation (rehandshake), the server sent a certificate with an error.
Note: this error is not in the -2xx range so that it won't be handled as a certificate error.
CertErrorInSslRenegotiationError
-116
CERT_ERROR_IN_SSL_RENEGOTIATION
const err = new chromiumNetErrors.CertErrorInSslRenegotiationError();
// or
const Err = chromiumNetErrors.getErrorByCode(-116);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_ERROR_IN_SSL_RENEGOTIATION');
const err = new Err();
The SSL handshake failed because of a bad or missing client certificate.
BadSslClientAuthCertError
-117
BAD_SSL_CLIENT_AUTH_CERT
const err = new chromiumNetErrors.BadSslClientAuthCertError();
// or
const Err = chromiumNetErrors.getErrorByCode(-117);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('BAD_SSL_CLIENT_AUTH_CERT');
const err = new Err();
A connection attempt timed out.
ConnectionTimedOutError
-118
CONNECTION_TIMED_OUT
const err = new chromiumNetErrors.ConnectionTimedOutError();
// or
const Err = chromiumNetErrors.getErrorByCode(-118);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONNECTION_TIMED_OUT');
const err = new Err();
There are too many pending DNS resolves, so a request in the queue was aborted.
HostResolverQueueTooLargeError
-119
HOST_RESOLVER_QUEUE_TOO_LARGE
const err = new chromiumNetErrors.HostResolverQueueTooLargeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-119);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HOST_RESOLVER_QUEUE_TOO_LARGE');
const err = new Err();
Failed establishing a connection to the SOCKS proxy server for a target host.
SocksConnectionFailedError
-120
SOCKS_CONNECTION_FAILED
const err = new chromiumNetErrors.SocksConnectionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-120);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKS_CONNECTION_FAILED');
const err = new Err();
The SOCKS proxy server failed establishing connection to the target host because that host is unreachable.
SocksConnectionHostUnreachableError
-121
SOCKS_CONNECTION_HOST_UNREACHABLE
const err = new chromiumNetErrors.SocksConnectionHostUnreachableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-121);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKS_CONNECTION_HOST_UNREACHABLE');
const err = new Err();
The request to negotiate an alternate protocol failed.
AlpnNegotiationFailedError
-122
ALPN_NEGOTIATION_FAILED
const err = new chromiumNetErrors.AlpnNegotiationFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-122);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ALPN_NEGOTIATION_FAILED');
const err = new Err();
The peer sent an SSL no_renegotiation alert message.
SslNoRenegotiationError
-123
SSL_NO_RENEGOTIATION
const err = new chromiumNetErrors.SslNoRenegotiationError();
// or
const Err = chromiumNetErrors.getErrorByCode(-123);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_NO_RENEGOTIATION');
const err = new Err();
Winsock sometimes reports more data written than passed. This is probably due to a broken LSP.
WinsockUnexpectedWrittenBytesError
-124
WINSOCK_UNEXPECTED_WRITTEN_BYTES
const err = new chromiumNetErrors.WinsockUnexpectedWrittenBytesError();
// or
const Err = chromiumNetErrors.getErrorByCode(-124);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('WINSOCK_UNEXPECTED_WRITTEN_BYTES');
const err = new Err();
An SSL peer sent us a fatal decompression_failure alert. This typically occurs when a peer selects DEFLATE compression in the mistaken belief that it supports it.
SslDecompressionFailureAlertError
-125
SSL_DECOMPRESSION_FAILURE_ALERT
const err = new chromiumNetErrors.SslDecompressionFailureAlertError();
// or
const Err = chromiumNetErrors.getErrorByCode(-125);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_DECOMPRESSION_FAILURE_ALERT');
const err = new Err();
An SSL peer sent us a fatal bad_record_mac alert. This has been observed from servers with buggy DEFLATE support.
SslBadRecordMacAlertError
-126
SSL_BAD_RECORD_MAC_ALERT
const err = new chromiumNetErrors.SslBadRecordMacAlertError();
// or
const Err = chromiumNetErrors.getErrorByCode(-126);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_BAD_RECORD_MAC_ALERT');
const err = new Err();
The proxy requested authentication (for tunnel establishment).
ProxyAuthRequestedError
-127
PROXY_AUTH_REQUESTED
const err = new chromiumNetErrors.ProxyAuthRequestedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-127);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PROXY_AUTH_REQUESTED');
const err = new Err();
Could not create a connection to the proxy server. An error occurred either in resolving its name, or in connecting a socket to it. Note that this does NOT include failures during the actual "CONNECT" method of an HTTP proxy.
ProxyConnectionFailedError
-130
PROXY_CONNECTION_FAILED
const err = new chromiumNetErrors.ProxyConnectionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-130);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PROXY_CONNECTION_FAILED');
const err = new Err();
A mandatory proxy configuration could not be used. Currently this means that a mandatory PAC script could not be fetched, parsed or executed.
MandatoryProxyConfigurationFailedError
-131
MANDATORY_PROXY_CONFIGURATION_FAILED
const err = new chromiumNetErrors.MandatoryProxyConfigurationFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-131);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('MANDATORY_PROXY_CONFIGURATION_FAILED');
const err = new Err();
We've hit the max socket limit for the socket pool while preconnecting. We don't bother trying to preconnect more sockets.
PreconnectMaxSocketLimitError
-133
PRECONNECT_MAX_SOCKET_LIMIT
const err = new chromiumNetErrors.PreconnectMaxSocketLimitError();
// or
const Err = chromiumNetErrors.getErrorByCode(-133);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PRECONNECT_MAX_SOCKET_LIMIT');
const err = new Err();
The permission to use the SSL client certificate's private key was denied.
SslClientAuthPrivateKeyAccessDeniedError
-134
SSL_CLIENT_AUTH_PRIVATE_KEY_ACCESS_DENIED
const err = new chromiumNetErrors.SslClientAuthPrivateKeyAccessDeniedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-134);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_CLIENT_AUTH_PRIVATE_KEY_ACCESS_DENIED');
const err = new Err();
The SSL client certificate has no private key.
SslClientAuthCertNoPrivateKeyError
-135
SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY
const err = new chromiumNetErrors.SslClientAuthCertNoPrivateKeyError();
// or
const Err = chromiumNetErrors.getErrorByCode(-135);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY');
const err = new Err();
The certificate presented by the HTTPS Proxy was invalid.
ProxyCertificateInvalidError
-136
PROXY_CERTIFICATE_INVALID
const err = new chromiumNetErrors.ProxyCertificateInvalidError();
// or
const Err = chromiumNetErrors.getErrorByCode(-136);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PROXY_CERTIFICATE_INVALID');
const err = new Err();
An error occurred when trying to do a name resolution (DNS).
NameResolutionFailedError
-137
NAME_RESOLUTION_FAILED
const err = new chromiumNetErrors.NameResolutionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-137);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NAME_RESOLUTION_FAILED');
const err = new Err();
Permission to access the network was denied. This is used to distinguish errors that were most likely caused by a firewall from other access denied errors. See also ERR_ACCESS_DENIED.
NetworkAccessDeniedError
-138
NETWORK_ACCESS_DENIED
const err = new chromiumNetErrors.NetworkAccessDeniedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-138);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NETWORK_ACCESS_DENIED');
const err = new Err();
The request throttler module cancelled this request to avoid DDOS.
TemporarilyThrottledError
-139
TEMPORARILY_THROTTLED
const err = new chromiumNetErrors.TemporarilyThrottledError();
// or
const Err = chromiumNetErrors.getErrorByCode(-139);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TEMPORARILY_THROTTLED');
const err = new Err();
A request to create an SSL tunnel connection through the HTTPS proxy received a 302 (temporary redirect) response. The response body might include a description of why the request failed.
TODO(https://crbug.com/928551): This is deprecated and should not be used by new code.
HttpsProxyTunnelResponseRedirectError
-140
HTTPS_PROXY_TUNNEL_RESPONSE_REDIRECT
const err = new chromiumNetErrors.HttpsProxyTunnelResponseRedirectError();
// or
const Err = chromiumNetErrors.getErrorByCode(-140);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTPS_PROXY_TUNNEL_RESPONSE_REDIRECT');
const err = new Err();
We were unable to sign the CertificateVerify data of an SSL client auth handshake with the client certificate's private key.
Possible causes for this include the user implicitly or explicitly denying access to the private key, the private key may not be valid for signing, the key may be relying on a cached handle which is no longer valid, or the CSP won't allow arbitrary data to be signed.
SslClientAuthSignatureFailedError
-141
SSL_CLIENT_AUTH_SIGNATURE_FAILED
const err = new chromiumNetErrors.SslClientAuthSignatureFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-141);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_CLIENT_AUTH_SIGNATURE_FAILED');
const err = new Err();
The message was too large for the transport. (for example a UDP message which exceeds size threshold).
MsgTooBigError
-142
MSG_TOO_BIG
const err = new chromiumNetErrors.MsgTooBigError();
// or
const Err = chromiumNetErrors.getErrorByCode(-142);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('MSG_TOO_BIG');
const err = new Err();
Websocket protocol error. Indicates that we are terminating the connection due to a malformed frame or other protocol violation.
WsProtocolError
-145
WS_PROTOCOL_ERROR
const err = new chromiumNetErrors.WsProtocolError();
// or
const Err = chromiumNetErrors.getErrorByCode(-145);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('WS_PROTOCOL_ERROR');
const err = new Err();
Returned when attempting to bind an address that is already in use.
AddressInUseError
-147
ADDRESS_IN_USE
const err = new chromiumNetErrors.AddressInUseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-147);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ADDRESS_IN_USE');
const err = new Err();
An operation failed because the SSL handshake has not completed.
SslHandshakeNotCompletedError
-148
SSL_HANDSHAKE_NOT_COMPLETED
const err = new chromiumNetErrors.SslHandshakeNotCompletedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-148);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_HANDSHAKE_NOT_COMPLETED');
const err = new Err();
SSL peer's public key is invalid.
SslBadPeerPublicKeyError
-149
SSL_BAD_PEER_PUBLIC_KEY
const err = new chromiumNetErrors.SslBadPeerPublicKeyError();
// or
const Err = chromiumNetErrors.getErrorByCode(-149);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_BAD_PEER_PUBLIC_KEY');
const err = new Err();
The certificate didn't match the built-in public key pins for the host name. The pins are set in net/http/transport_security_state.cc and require that one of a set of public keys exist on the path from the leaf to the root.
SslPinnedKeyNotInCertChainError
-150
SSL_PINNED_KEY_NOT_IN_CERT_CHAIN
const err = new chromiumNetErrors.SslPinnedKeyNotInCertChainError();
// or
const Err = chromiumNetErrors.getErrorByCode(-150);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_PINNED_KEY_NOT_IN_CERT_CHAIN');
const err = new Err();
Server request for client certificate did not contain any types we support.
ClientAuthCertTypeUnsupportedError
-151
CLIENT_AUTH_CERT_TYPE_UNSUPPORTED
const err = new chromiumNetErrors.ClientAuthCertTypeUnsupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-151);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CLIENT_AUTH_CERT_TYPE_UNSUPPORTED');
const err = new Err();
An SSL peer sent us a fatal decrypt_error alert. This typically occurs when a peer could not correctly verify a signature (in CertificateVerify or ServerKeyExchange) or validate a Finished message.
SslDecryptErrorAlertError
-153
SSL_DECRYPT_ERROR_ALERT
const err = new chromiumNetErrors.SslDecryptErrorAlertError();
// or
const Err = chromiumNetErrors.getErrorByCode(-153);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_DECRYPT_ERROR_ALERT');
const err = new Err();
There are too many pending WebSocketJob instances, so the new job was not pushed to the queue.
WsThrottleQueueTooLargeError
-154
WS_THROTTLE_QUEUE_TOO_LARGE
const err = new chromiumNetErrors.WsThrottleQueueTooLargeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-154);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('WS_THROTTLE_QUEUE_TOO_LARGE');
const err = new Err();
The SSL server certificate changed in a renegotiation.
SslServerCertChangedError
-156
SSL_SERVER_CERT_CHANGED
const err = new chromiumNetErrors.SslServerCertChangedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-156);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_SERVER_CERT_CHANGED');
const err = new Err();
The SSL server sent us a fatal unrecognized_name alert.
SslUnrecognizedNameAlertError
-159
SSL_UNRECOGNIZED_NAME_ALERT
const err = new chromiumNetErrors.SslUnrecognizedNameAlertError();
// or
const Err = chromiumNetErrors.getErrorByCode(-159);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_UNRECOGNIZED_NAME_ALERT');
const err = new Err();
Failed to set the socket's receive buffer size as requested.
SocketSetReceiveBufferSizeError
-160
SOCKET_SET_RECEIVE_BUFFER_SIZE_ERROR
const err = new chromiumNetErrors.SocketSetReceiveBufferSizeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-160);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKET_SET_RECEIVE_BUFFER_SIZE_ERROR');
const err = new Err();
Failed to set the socket's send buffer size as requested.
SocketSetSendBufferSizeError
-161
SOCKET_SET_SEND_BUFFER_SIZE_ERROR
const err = new chromiumNetErrors.SocketSetSendBufferSizeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-161);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKET_SET_SEND_BUFFER_SIZE_ERROR');
const err = new Err();
Failed to set the socket's receive buffer size as requested, despite success return code from setsockopt.
SocketReceiveBufferSizeUnchangeableError
-162
SOCKET_RECEIVE_BUFFER_SIZE_UNCHANGEABLE
const err = new chromiumNetErrors.SocketReceiveBufferSizeUnchangeableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-162);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKET_RECEIVE_BUFFER_SIZE_UNCHANGEABLE');
const err = new Err();
Failed to set the socket's send buffer size as requested, despite success return code from setsockopt.
SocketSendBufferSizeUnchangeableError
-163
SOCKET_SEND_BUFFER_SIZE_UNCHANGEABLE
const err = new chromiumNetErrors.SocketSendBufferSizeUnchangeableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-163);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SOCKET_SEND_BUFFER_SIZE_UNCHANGEABLE');
const err = new Err();
Failed to import a client certificate from the platform store into the SSL library.
SslClientAuthCertBadFormatError
-164
SSL_CLIENT_AUTH_CERT_BAD_FORMAT
const err = new chromiumNetErrors.SslClientAuthCertBadFormatError();
// or
const Err = chromiumNetErrors.getErrorByCode(-164);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_CLIENT_AUTH_CERT_BAD_FORMAT');
const err = new Err();
Resolving a hostname to an IP address list included the IPv4 address "127.0.53.53". This is a special IP address which ICANN has recommended to indicate there was a name collision, and alert admins to a potential problem.
IcannNameCollisionError
-166
ICANN_NAME_COLLISION
const err = new chromiumNetErrors.IcannNameCollisionError();
// or
const Err = chromiumNetErrors.getErrorByCode(-166);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ICANN_NAME_COLLISION');
const err = new Err();
The SSL server presented a certificate which could not be decoded. This is not a certificate error code as no X509Certificate object is available. This error is fatal.
SslServerCertBadFormatError
-167
SSL_SERVER_CERT_BAD_FORMAT
const err = new chromiumNetErrors.SslServerCertBadFormatError();
// or
const Err = chromiumNetErrors.getErrorByCode(-167);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_SERVER_CERT_BAD_FORMAT');
const err = new Err();
Certificate Transparency: Received a signed tree head that failed to parse.
CtSthParsingFailedError
-168
CT_STH_PARSING_FAILED
const err = new chromiumNetErrors.CtSthParsingFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-168);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CT_STH_PARSING_FAILED');
const err = new Err();
Certificate Transparency: Received a signed tree head whose JSON parsing was OK but was missing some of the fields.
CtSthIncompleteError
-169
CT_STH_INCOMPLETE
const err = new chromiumNetErrors.CtSthIncompleteError();
// or
const Err = chromiumNetErrors.getErrorByCode(-169);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CT_STH_INCOMPLETE');
const err = new Err();
The attempt to reuse a connection to send proxy auth credentials failed before the AuthController was used to generate credentials. The caller should reuse the controller with a new connection. This error is only used internally by the network stack.
UnableToReuseConnectionForProxyAuthError
-170
UNABLE_TO_REUSE_CONNECTION_FOR_PROXY_AUTH
const err = new chromiumNetErrors.UnableToReuseConnectionForProxyAuthError();
// or
const Err = chromiumNetErrors.getErrorByCode(-170);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNABLE_TO_REUSE_CONNECTION_FOR_PROXY_AUTH');
const err = new Err();
Certificate Transparency: Failed to parse the received consistency proof.
CtConsistencyProofParsingFailedError
-171
CT_CONSISTENCY_PROOF_PARSING_FAILED
const err = new chromiumNetErrors.CtConsistencyProofParsingFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-171);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CT_CONSISTENCY_PROOF_PARSING_FAILED');
const err = new Err();
The SSL server required an unsupported cipher suite that has since been removed. This error will temporarily be signaled on a fallback for one or two releases immediately following a cipher suite's removal, after which the fallback will be removed.
SslObsoleteCipherError
-172
SSL_OBSOLETE_CIPHER
const err = new chromiumNetErrors.SslObsoleteCipherError();
// or
const Err = chromiumNetErrors.getErrorByCode(-172);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_OBSOLETE_CIPHER');
const err = new Err();
When a WebSocket handshake is done successfully and the connection has been upgraded, the URLRequest is cancelled with this error code.
WsUpgradeError
-173
WS_UPGRADE
const err = new chromiumNetErrors.WsUpgradeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-173);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('WS_UPGRADE');
const err = new Err();
Socket ReadIfReady support is not implemented. This error should not be user visible, because the normal Read() method is used as a fallback.
ReadIfReadyNotImplementedError
-174
READ_IF_READY_NOT_IMPLEMENTED
const err = new chromiumNetErrors.ReadIfReadyNotImplementedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-174);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('READ_IF_READY_NOT_IMPLEMENTED');
const err = new Err();
No socket buffer space is available.
NoBufferSpaceError
-176
NO_BUFFER_SPACE
const err = new chromiumNetErrors.NoBufferSpaceError();
// or
const Err = chromiumNetErrors.getErrorByCode(-176);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NO_BUFFER_SPACE');
const err = new Err();
There were no common signature algorithms between our client certificate private key and the server's preferences.
SslClientAuthNoCommonAlgorithmsError
-177
SSL_CLIENT_AUTH_NO_COMMON_ALGORITHMS
const err = new chromiumNetErrors.SslClientAuthNoCommonAlgorithmsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-177);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_CLIENT_AUTH_NO_COMMON_ALGORITHMS');
const err = new Err();
TLS 1.3 early data was rejected by the server. This will be received before any data is returned from the socket. The request should be retried with early data disabled.
EarlyDataRejectedError
-178
EARLY_DATA_REJECTED
const err = new chromiumNetErrors.EarlyDataRejectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-178);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('EARLY_DATA_REJECTED');
const err = new Err();
TLS 1.3 early data was offered, but the server responded with TLS 1.2 or earlier. This is an internal error code to account for a backwards-compatibility issue with early data and TLS 1.2. It will be received before any data is returned from the socket. The request should be retried with early data disabled.
See https://tools.ietf.org/html/rfc8446#appendix-D.3 for details.
WrongVersionOnEarlyDataError
-179
WRONG_VERSION_ON_EARLY_DATA
const err = new chromiumNetErrors.WrongVersionOnEarlyDataError();
// or
const Err = chromiumNetErrors.getErrorByCode(-179);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('WRONG_VERSION_ON_EARLY_DATA');
const err = new Err();
TLS 1.3 was enabled, but a lower version was negotiated and the server returned a value indicating it supported TLS 1.3. This is part of a security check in TLS 1.3, but it may also indicate the user is behind a buggy TLS-terminating proxy which implemented TLS 1.2 incorrectly. (See https://crbug.com/boringssl/226.)
Tls13DowngradeDetectedError
-180
TLS13_DOWNGRADE_DETECTED
const err = new chromiumNetErrors.Tls13DowngradeDetectedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-180);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TLS13_DOWNGRADE_DETECTED');
const err = new Err();
The server's certificate has a keyUsage extension incompatible with the negotiated TLS key exchange method.
SslKeyUsageIncompatibleError
-181
SSL_KEY_USAGE_INCOMPATIBLE
const err = new chromiumNetErrors.SslKeyUsageIncompatibleError();
// or
const Err = chromiumNetErrors.getErrorByCode(-181);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_KEY_USAGE_INCOMPATIBLE');
const err = new Err();
The server responded with a certificate whose common name did not match the host name. This could mean:
An attacker has redirected our traffic to their server and is presenting a certificate for which they know the private key.
The server is misconfigured and responding with the wrong cert.
The user is on a wireless network and is being redirected to the network's login page.
The OS has used a DNS search suffix and the server doesn't have a certificate for the abbreviated name in the address bar.
CertCommonNameInvalidError
-200
CERT_COMMON_NAME_INVALID
const err = new chromiumNetErrors.CertCommonNameInvalidError();
// or
const Err = chromiumNetErrors.getErrorByCode(-200);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_COMMON_NAME_INVALID');
const err = new Err();
The server responded with a certificate that, by our clock, appears to either not yet be valid or to have expired. This could mean:
An attacker is presenting an old certificate for which they have managed to obtain the private key.
The server is misconfigured and is not presenting a valid cert.
Our clock is wrong.
CertDateInvalidError
-201
CERT_DATE_INVALID
const err = new chromiumNetErrors.CertDateInvalidError();
// or
const Err = chromiumNetErrors.getErrorByCode(-201);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_DATE_INVALID');
const err = new Err();
The server responded with a certificate that is signed by an authority we don't trust. The could mean:
An attacker has substituted the real certificate for a cert that contains their public key and is signed by their cousin.
The server operator has a legitimate certificate from a CA we don't know about, but should trust.
The server is presenting a self-signed certificate, providing no defense against active attackers (but foiling passive attackers).
CertAuthorityInvalidError
-202
CERT_AUTHORITY_INVALID
const err = new chromiumNetErrors.CertAuthorityInvalidError();
// or
const Err = chromiumNetErrors.getErrorByCode(-202);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_AUTHORITY_INVALID');
const err = new Err();
The server responded with a certificate that contains errors. This error is not recoverable.
MSDN describes this error as follows: "The SSL certificate contains errors." NOTE: It's unclear how this differs from ERR_CERT_INVALID. For consistency, use that code instead of this one from now on.
CertContainsErrorsError
-203
CERT_CONTAINS_ERRORS
const err = new chromiumNetErrors.CertContainsErrorsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-203);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_CONTAINS_ERRORS');
const err = new Err();
The certificate has no mechanism for determining if it is revoked. In effect, this certificate cannot be revoked.
CertNoRevocationMechanismError
-204
CERT_NO_REVOCATION_MECHANISM
const err = new chromiumNetErrors.CertNoRevocationMechanismError();
// or
const Err = chromiumNetErrors.getErrorByCode(-204);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_NO_REVOCATION_MECHANISM');
const err = new Err();
Revocation information for the security certificate for this site is not available. This could mean:
An attacker has compromised the private key in the certificate and is blocking our attempt to find out that the cert was revoked.
The certificate is unrevoked, but the revocation server is busy or unavailable.
CertUnableToCheckRevocationError
-205
CERT_UNABLE_TO_CHECK_REVOCATION
const err = new chromiumNetErrors.CertUnableToCheckRevocationError();
// or
const Err = chromiumNetErrors.getErrorByCode(-205);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_UNABLE_TO_CHECK_REVOCATION');
const err = new Err();
The server responded with a certificate has been revoked. We have the capability to ignore this error, but it is probably not the thing to do.
CertRevokedError
-206
CERT_REVOKED
const err = new chromiumNetErrors.CertRevokedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-206);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_REVOKED');
const err = new Err();
The server responded with a certificate that is invalid. This error is not recoverable.
MSDN describes this error as follows: "The SSL certificate is invalid."
CertInvalidError
-207
CERT_INVALID
const err = new chromiumNetErrors.CertInvalidError();
// or
const Err = chromiumNetErrors.getErrorByCode(-207);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_INVALID');
const err = new Err();
The server responded with a certificate that is signed using a weak signature algorithm.
CertWeakSignatureAlgorithmError
-208
CERT_WEAK_SIGNATURE_ALGORITHM
const err = new chromiumNetErrors.CertWeakSignatureAlgorithmError();
// or
const Err = chromiumNetErrors.getErrorByCode(-208);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_WEAK_SIGNATURE_ALGORITHM');
const err = new Err();
The host name specified in the certificate is not unique.
CertNonUniqueNameError
-210
CERT_NON_UNIQUE_NAME
const err = new chromiumNetErrors.CertNonUniqueNameError();
// or
const Err = chromiumNetErrors.getErrorByCode(-210);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_NON_UNIQUE_NAME');
const err = new Err();
The server responded with a certificate that contains a weak key (e.g. a too-small RSA key).
CertWeakKeyError
-211
CERT_WEAK_KEY
const err = new chromiumNetErrors.CertWeakKeyError();
// or
const Err = chromiumNetErrors.getErrorByCode(-211);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_WEAK_KEY');
const err = new Err();
The certificate claimed DNS names that are in violation of name constraints.
CertNameConstraintViolationError
-212
CERT_NAME_CONSTRAINT_VIOLATION
const err = new chromiumNetErrors.CertNameConstraintViolationError();
// or
const Err = chromiumNetErrors.getErrorByCode(-212);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_NAME_CONSTRAINT_VIOLATION');
const err = new Err();
The certificate's validity period is too long.
CertValidityTooLongError
-213
CERT_VALIDITY_TOO_LONG
const err = new chromiumNetErrors.CertValidityTooLongError();
// or
const Err = chromiumNetErrors.getErrorByCode(-213);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_VALIDITY_TOO_LONG');
const err = new Err();
Certificate Transparency was required for this connection, but the server did not provide CT information that complied with the policy.
CertificateTransparencyRequiredError
-214
CERTIFICATE_TRANSPARENCY_REQUIRED
const err = new chromiumNetErrors.CertificateTransparencyRequiredError();
// or
const Err = chromiumNetErrors.getErrorByCode(-214);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERTIFICATE_TRANSPARENCY_REQUIRED');
const err = new Err();
The certificate chained to a legacy Symantec root that is no longer trusted. https://g.co/chrome/symantecpkicerts
CertSymantecLegacyError
-215
CERT_SYMANTEC_LEGACY
const err = new chromiumNetErrors.CertSymantecLegacyError();
// or
const Err = chromiumNetErrors.getErrorByCode(-215);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_SYMANTEC_LEGACY');
const err = new Err();
The certificate is known to be used for interception by an entity other the device owner.
CertKnownInterceptionBlockedError
-217
CERT_KNOWN_INTERCEPTION_BLOCKED
const err = new chromiumNetErrors.CertKnownInterceptionBlockedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-217);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_KNOWN_INTERCEPTION_BLOCKED');
const err = new Err();
The connection uses an obsolete version of SSL/TLS.
SslObsoleteVersionError
-218
SSL_OBSOLETE_VERSION
const err = new chromiumNetErrors.SslObsoleteVersionError();
// or
const Err = chromiumNetErrors.getErrorByCode(-218);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SSL_OBSOLETE_VERSION');
const err = new Err();
The value immediately past the last certificate error code.
CertEndError
-219
CERT_END
const err = new chromiumNetErrors.CertEndError();
// or
const Err = chromiumNetErrors.getErrorByCode(-219);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_END');
const err = new Err();
The URL is invalid.
InvalidUrlError
-300
INVALID_URL
const err = new chromiumNetErrors.InvalidUrlError();
// or
const Err = chromiumNetErrors.getErrorByCode(-300);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_URL');
const err = new Err();
The scheme of the URL is disallowed.
DisallowedUrlSchemeError
-301
DISALLOWED_URL_SCHEME
const err = new chromiumNetErrors.DisallowedUrlSchemeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-301);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DISALLOWED_URL_SCHEME');
const err = new Err();
The scheme of the URL is unknown.
UnknownUrlSchemeError
-302
UNKNOWN_URL_SCHEME
const err = new chromiumNetErrors.UnknownUrlSchemeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-302);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNKNOWN_URL_SCHEME');
const err = new Err();
Attempting to load an URL resulted in a redirect to an invalid URL.
InvalidRedirectError
-303
INVALID_REDIRECT
const err = new chromiumNetErrors.InvalidRedirectError();
// or
const Err = chromiumNetErrors.getErrorByCode(-303);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_REDIRECT');
const err = new Err();
Attempting to load an URL resulted in too many redirects.
TooManyRedirectsError
-310
TOO_MANY_REDIRECTS
const err = new chromiumNetErrors.TooManyRedirectsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-310);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TOO_MANY_REDIRECTS');
const err = new Err();
Attempting to load an URL resulted in an unsafe redirect (e.g., a redirect to file:// is considered unsafe).
UnsafeRedirectError
-311
UNSAFE_REDIRECT
const err = new chromiumNetErrors.UnsafeRedirectError();
// or
const Err = chromiumNetErrors.getErrorByCode(-311);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNSAFE_REDIRECT');
const err = new Err();
Attempting to load an URL with an unsafe port number. These are port numbers that correspond to services, which are not robust to spurious input that may be constructed as a result of an allowed web construct (e.g., HTTP looks a lot like SMTP, so form submission to port 25 is denied).
UnsafePortError
-312
UNSAFE_PORT
const err = new chromiumNetErrors.UnsafePortError();
// or
const Err = chromiumNetErrors.getErrorByCode(-312);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNSAFE_PORT');
const err = new Err();
The server's response was invalid.
InvalidResponseError
-320
INVALID_RESPONSE
const err = new chromiumNetErrors.InvalidResponseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-320);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_RESPONSE');
const err = new Err();
Error in chunked transfer encoding.
InvalidChunkedEncodingError
-321
INVALID_CHUNKED_ENCODING
const err = new chromiumNetErrors.InvalidChunkedEncodingError();
// or
const Err = chromiumNetErrors.getErrorByCode(-321);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_CHUNKED_ENCODING');
const err = new Err();
The server did not support the request method.
MethodNotSupportedError
-322
METHOD_NOT_SUPPORTED
const err = new chromiumNetErrors.MethodNotSupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-322);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('METHOD_NOT_SUPPORTED');
const err = new Err();
The response was 407 (Proxy Authentication Required), yet we did not send the request to a proxy.
UnexpectedProxyAuthError
-323
UNEXPECTED_PROXY_AUTH
const err = new chromiumNetErrors.UnexpectedProxyAuthError();
// or
const Err = chromiumNetErrors.getErrorByCode(-323);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNEXPECTED_PROXY_AUTH');
const err = new Err();
The server closed the connection without sending any data.
EmptyResponseError
-324
EMPTY_RESPONSE
const err = new chromiumNetErrors.EmptyResponseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-324);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('EMPTY_RESPONSE');
const err = new Err();
The headers section of the response is too large.
ResponseHeadersTooBigError
-325
RESPONSE_HEADERS_TOO_BIG
const err = new chromiumNetErrors.ResponseHeadersTooBigError();
// or
const Err = chromiumNetErrors.getErrorByCode(-325);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('RESPONSE_HEADERS_TOO_BIG');
const err = new Err();
The evaluation of the PAC script failed.
PacScriptFailedError
-327
PAC_SCRIPT_FAILED
const err = new chromiumNetErrors.PacScriptFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-327);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PAC_SCRIPT_FAILED');
const err = new Err();
The response was 416 (Requested range not satisfiable) and the server cannot satisfy the range requested.
RequestRangeNotSatisfiableError
-328
REQUEST_RANGE_NOT_SATISFIABLE
const err = new chromiumNetErrors.RequestRangeNotSatisfiableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-328);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('REQUEST_RANGE_NOT_SATISFIABLE');
const err = new Err();
The identity used for authentication is invalid.
MalformedIdentityError
-329
MALFORMED_IDENTITY
const err = new chromiumNetErrors.MalformedIdentityError();
// or
const Err = chromiumNetErrors.getErrorByCode(-329);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('MALFORMED_IDENTITY');
const err = new Err();
Content decoding of the response body failed.
ContentDecodingFailedError
-330
CONTENT_DECODING_FAILED
const err = new chromiumNetErrors.ContentDecodingFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-330);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONTENT_DECODING_FAILED');
const err = new Err();
An operation could not be completed because all network IO is suspended.
NetworkIoSuspendedError
-331
NETWORK_IO_SUSPENDED
const err = new chromiumNetErrors.NetworkIoSuspendedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-331);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NETWORK_IO_SUSPENDED');
const err = new Err();
FLIP data received without receiving a SYN_REPLY on the stream.
SynReplyNotReceivedError
-332
SYN_REPLY_NOT_RECEIVED
const err = new chromiumNetErrors.SynReplyNotReceivedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-332);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SYN_REPLY_NOT_RECEIVED');
const err = new Err();
Converting the response to target encoding failed.
EncodingConversionFailedError
-333
ENCODING_CONVERSION_FAILED
const err = new chromiumNetErrors.EncodingConversionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-333);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ENCODING_CONVERSION_FAILED');
const err = new Err();
The server sent an FTP directory listing in a format we do not understand.
UnrecognizedFtpDirectoryListingFormatError
-334
UNRECOGNIZED_FTP_DIRECTORY_LISTING_FORMAT
const err = new chromiumNetErrors.UnrecognizedFtpDirectoryListingFormatError();
// or
const Err = chromiumNetErrors.getErrorByCode(-334);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNRECOGNIZED_FTP_DIRECTORY_LISTING_FORMAT');
const err = new Err();
There are no supported proxies in the provided list.
NoSupportedProxiesError
-336
NO_SUPPORTED_PROXIES
const err = new chromiumNetErrors.NoSupportedProxiesError();
// or
const Err = chromiumNetErrors.getErrorByCode(-336);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NO_SUPPORTED_PROXIES');
const err = new Err();
There is an HTTP/2 protocol error.
Http2ProtocolError
-337
HTTP2_PROTOCOL_ERROR
const err = new chromiumNetErrors.Http2ProtocolError();
// or
const Err = chromiumNetErrors.getErrorByCode(-337);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_PROTOCOL_ERROR');
const err = new Err();
Credentials could not be established during HTTP Authentication.
InvalidAuthCredentialsError
-338
INVALID_AUTH_CREDENTIALS
const err = new chromiumNetErrors.InvalidAuthCredentialsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-338);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_AUTH_CREDENTIALS');
const err = new Err();
An HTTP Authentication scheme was tried which is not supported on this machine.
UnsupportedAuthSchemeError
-339
UNSUPPORTED_AUTH_SCHEME
const err = new chromiumNetErrors.UnsupportedAuthSchemeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-339);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNSUPPORTED_AUTH_SCHEME');
const err = new Err();
Detecting the encoding of the response failed.
EncodingDetectionFailedError
-340
ENCODING_DETECTION_FAILED
const err = new chromiumNetErrors.EncodingDetectionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-340);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ENCODING_DETECTION_FAILED');
const err = new Err();
(GSSAPI) No Kerberos credentials were available during HTTP Authentication.
MissingAuthCredentialsError
-341
MISSING_AUTH_CREDENTIALS
const err = new chromiumNetErrors.MissingAuthCredentialsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-341);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('MISSING_AUTH_CREDENTIALS');
const err = new Err();
An unexpected, but documented, SSPI or GSSAPI status code was returned.
UnexpectedSecurityLibraryStatusError
-342
UNEXPECTED_SECURITY_LIBRARY_STATUS
const err = new chromiumNetErrors.UnexpectedSecurityLibraryStatusError();
// or
const Err = chromiumNetErrors.getErrorByCode(-342);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNEXPECTED_SECURITY_LIBRARY_STATUS');
const err = new Err();
The environment was not set up correctly for authentication (for example, no KDC could be found or the principal is unknown.
MisconfiguredAuthEnvironmentError
-343
MISCONFIGURED_AUTH_ENVIRONMENT
const err = new chromiumNetErrors.MisconfiguredAuthEnvironmentError();
// or
const Err = chromiumNetErrors.getErrorByCode(-343);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('MISCONFIGURED_AUTH_ENVIRONMENT');
const err = new Err();
An undocumented SSPI or GSSAPI status code was returned.
UndocumentedSecurityLibraryStatusError
-344
UNDOCUMENTED_SECURITY_LIBRARY_STATUS
const err = new chromiumNetErrors.UndocumentedSecurityLibraryStatusError();
// or
const Err = chromiumNetErrors.getErrorByCode(-344);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('UNDOCUMENTED_SECURITY_LIBRARY_STATUS');
const err = new Err();
The HTTP response was too big to drain.
ResponseBodyTooBigToDrainError
-345
RESPONSE_BODY_TOO_BIG_TO_DRAIN
const err = new chromiumNetErrors.ResponseBodyTooBigToDrainError();
// or
const Err = chromiumNetErrors.getErrorByCode(-345);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('RESPONSE_BODY_TOO_BIG_TO_DRAIN');
const err = new Err();
The HTTP response contained multiple distinct Content-Length headers.
ResponseHeadersMultipleContentLengthError
-346
RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH
const err = new chromiumNetErrors.ResponseHeadersMultipleContentLengthError();
// or
const Err = chromiumNetErrors.getErrorByCode(-346);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('RESPONSE_HEADERS_MULTIPLE_CONTENT_LENGTH');
const err = new Err();
HTTP/2 headers have been received, but not all of them - status or version headers are missing, so we're expecting additional frames to complete them.
IncompleteHttp2HeadersError
-347
INCOMPLETE_HTTP2_HEADERS
const err = new chromiumNetErrors.IncompleteHttp2HeadersError();
// or
const Err = chromiumNetErrors.getErrorByCode(-347);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INCOMPLETE_HTTP2_HEADERS');
const err = new Err();
No PAC URL configuration could be retrieved from DHCP. This can indicate either a failure to retrieve the DHCP configuration, or that there was no PAC URL configured in DHCP.
PacNotInDhcpError
-348
PAC_NOT_IN_DHCP
const err = new chromiumNetErrors.PacNotInDhcpError();
// or
const Err = chromiumNetErrors.getErrorByCode(-348);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PAC_NOT_IN_DHCP');
const err = new Err();
The HTTP response contained multiple Content-Disposition headers.
ResponseHeadersMultipleContentDispositionError
-349
RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION
const err = new chromiumNetErrors.ResponseHeadersMultipleContentDispositionError();
// or
const Err = chromiumNetErrors.getErrorByCode(-349);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('RESPONSE_HEADERS_MULTIPLE_CONTENT_DISPOSITION');
const err = new Err();
The HTTP response contained multiple Location headers.
ResponseHeadersMultipleLocationError
-350
RESPONSE_HEADERS_MULTIPLE_LOCATION
const err = new chromiumNetErrors.ResponseHeadersMultipleLocationError();
// or
const Err = chromiumNetErrors.getErrorByCode(-350);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('RESPONSE_HEADERS_MULTIPLE_LOCATION');
const err = new Err();
HTTP/2 server refused the request without processing, and sent either a GOAWAY frame with error code NO_ERROR and Last-Stream-ID lower than the stream id corresponding to the request indicating that this request has not been processed yet, or a RST_STREAM frame with error code REFUSED_STREAM. Client MAY retry (on a different connection). See RFC7540 Section 8.1.4.
Http2ServerRefusedStreamError
-351
HTTP2_SERVER_REFUSED_STREAM
const err = new chromiumNetErrors.Http2ServerRefusedStreamError();
// or
const Err = chromiumNetErrors.getErrorByCode(-351);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_SERVER_REFUSED_STREAM');
const err = new Err();
HTTP/2 server didn't respond to the PING message.
Http2PingFailedError
-352
HTTP2_PING_FAILED
const err = new chromiumNetErrors.Http2PingFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-352);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_PING_FAILED');
const err = new Err();
The HTTP response body transferred fewer bytes than were advertised by the Content-Length header when the connection is closed.
ContentLengthMismatchError
-354
CONTENT_LENGTH_MISMATCH
const err = new chromiumNetErrors.ContentLengthMismatchError();
// or
const Err = chromiumNetErrors.getErrorByCode(-354);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONTENT_LENGTH_MISMATCH');
const err = new Err();
The HTTP response body is transferred with Chunked-Encoding, but the terminating zero-length chunk was never sent when the connection is closed.
IncompleteChunkedEncodingError
-355
INCOMPLETE_CHUNKED_ENCODING
const err = new chromiumNetErrors.IncompleteChunkedEncodingError();
// or
const Err = chromiumNetErrors.getErrorByCode(-355);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INCOMPLETE_CHUNKED_ENCODING');
const err = new Err();
There is a QUIC protocol error.
QuicProtocolError
-356
QUIC_PROTOCOL_ERROR
const err = new chromiumNetErrors.QuicProtocolError();
// or
const Err = chromiumNetErrors.getErrorByCode(-356);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('QUIC_PROTOCOL_ERROR');
const err = new Err();
The HTTP headers were truncated by an EOF.
ResponseHeadersTruncatedError
-357
RESPONSE_HEADERS_TRUNCATED
const err = new chromiumNetErrors.ResponseHeadersTruncatedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-357);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('RESPONSE_HEADERS_TRUNCATED');
const err = new Err();
The QUIC crytpo handshake failed. This means that the server was unable to read any requests sent, so they may be resent.
QuicHandshakeFailedError
-358
QUIC_HANDSHAKE_FAILED
const err = new chromiumNetErrors.QuicHandshakeFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-358);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('QUIC_HANDSHAKE_FAILED');
const err = new Err();
Transport security is inadequate for the HTTP/2 version.
Http2InadequateTransportSecurityError
-360
HTTP2_INADEQUATE_TRANSPORT_SECURITY
const err = new chromiumNetErrors.Http2InadequateTransportSecurityError();
// or
const Err = chromiumNetErrors.getErrorByCode(-360);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_INADEQUATE_TRANSPORT_SECURITY');
const err = new Err();
The peer violated HTTP/2 flow control.
Http2FlowControlError
-361
HTTP2_FLOW_CONTROL_ERROR
const err = new chromiumNetErrors.Http2FlowControlError();
// or
const Err = chromiumNetErrors.getErrorByCode(-361);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_FLOW_CONTROL_ERROR');
const err = new Err();
The peer sent an improperly sized HTTP/2 frame.
Http2FrameSizeError
-362
HTTP2_FRAME_SIZE_ERROR
const err = new chromiumNetErrors.Http2FrameSizeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-362);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_FRAME_SIZE_ERROR');
const err = new Err();
Decoding or encoding of compressed HTTP/2 headers failed.
Http2CompressionError
-363
HTTP2_COMPRESSION_ERROR
const err = new chromiumNetErrors.Http2CompressionError();
// or
const Err = chromiumNetErrors.getErrorByCode(-363);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_COMPRESSION_ERROR');
const err = new Err();
Proxy Auth Requested without a valid Client Socket Handle.
ProxyAuthRequestedWithNoConnectionError
-364
PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION
const err = new chromiumNetErrors.ProxyAuthRequestedWithNoConnectionError();
// or
const Err = chromiumNetErrors.getErrorByCode(-364);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PROXY_AUTH_REQUESTED_WITH_NO_CONNECTION');
const err = new Err();
HTTP_1_1_REQUIRED error code received on HTTP/2 session.
Http_1_1RequiredError
-365
HTTP_1_1_REQUIRED
const err = new chromiumNetErrors.Http_1_1RequiredError();
// or
const Err = chromiumNetErrors.getErrorByCode(-365);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP_1_1_REQUIRED');
const err = new Err();
HTTP_1_1_REQUIRED error code received on HTTP/2 session to proxy.
ProxyHttp_1_1RequiredError
-366
PROXY_HTTP_1_1_REQUIRED
const err = new chromiumNetErrors.ProxyHttp_1_1RequiredError();
// or
const Err = chromiumNetErrors.getErrorByCode(-366);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PROXY_HTTP_1_1_REQUIRED');
const err = new Err();
The PAC script terminated fatally and must be reloaded.
PacScriptTerminatedError
-367
PAC_SCRIPT_TERMINATED
const err = new chromiumNetErrors.PacScriptTerminatedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-367);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PAC_SCRIPT_TERMINATED');
const err = new Err();
The server was expected to return an HTTP/1.x response, but did not. Rather than treat it as HTTP/0.9, this error is returned.
InvalidHttpResponseError
-370
INVALID_HTTP_RESPONSE
const err = new chromiumNetErrors.InvalidHttpResponseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-370);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_HTTP_RESPONSE');
const err = new Err();
Initializing content decoding failed.
ContentDecodingInitFailedError
-371
CONTENT_DECODING_INIT_FAILED
const err = new chromiumNetErrors.ContentDecodingInitFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-371);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CONTENT_DECODING_INIT_FAILED');
const err = new Err();
Received HTTP/2 RST_STREAM frame with NO_ERROR error code. This error should be handled internally by HTTP/2 code, and should not make it above the SpdyStream layer.
Http2RstStreamNoErrorReceivedError
-372
HTTP2_RST_STREAM_NO_ERROR_RECEIVED
const err = new chromiumNetErrors.Http2RstStreamNoErrorReceivedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-372);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_RST_STREAM_NO_ERROR_RECEIVED');
const err = new Err();
The pushed stream claimed by the request is no longer available.
Http2PushedStreamNotAvailableError
-373
HTTP2_PUSHED_STREAM_NOT_AVAILABLE
const err = new chromiumNetErrors.Http2PushedStreamNotAvailableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-373);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_PUSHED_STREAM_NOT_AVAILABLE');
const err = new Err();
A pushed stream was claimed and later reset by the server. When this happens, the request should be retried.
Http2ClaimedPushedStreamResetByServerError
-374
HTTP2_CLAIMED_PUSHED_STREAM_RESET_BY_SERVER
const err = new chromiumNetErrors.Http2ClaimedPushedStreamResetByServerError();
// or
const Err = chromiumNetErrors.getErrorByCode(-374);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_CLAIMED_PUSHED_STREAM_RESET_BY_SERVER');
const err = new Err();
An HTTP transaction was retried too many times due for authentication or invalid certificates. This may be due to a bug in the net stack that would otherwise infinite loop, or if the server or proxy continually requests fresh credentials or presents a fresh invalid certificate.
TooManyRetriesError
-375
TOO_MANY_RETRIES
const err = new chromiumNetErrors.TooManyRetriesError();
// or
const Err = chromiumNetErrors.getErrorByCode(-375);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TOO_MANY_RETRIES');
const err = new Err();
Received an HTTP/2 frame on a closed stream.
Http2StreamClosedError
-376
HTTP2_STREAM_CLOSED
const err = new chromiumNetErrors.Http2StreamClosedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-376);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_STREAM_CLOSED');
const err = new Err();
Client is refusing an HTTP/2 stream.
Http2ClientRefusedStreamError
-377
HTTP2_CLIENT_REFUSED_STREAM
const err = new chromiumNetErrors.Http2ClientRefusedStreamError();
// or
const Err = chromiumNetErrors.getErrorByCode(-377);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_CLIENT_REFUSED_STREAM');
const err = new Err();
A pushed HTTP/2 stream was claimed by a request based on matching URL and request headers, but the pushed response headers do not match the request.
Http2PushedResponseDoesNotMatchError
-378
HTTP2_PUSHED_RESPONSE_DOES_NOT_MATCH
const err = new chromiumNetErrors.Http2PushedResponseDoesNotMatchError();
// or
const Err = chromiumNetErrors.getErrorByCode(-378);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP2_PUSHED_RESPONSE_DOES_NOT_MATCH');
const err = new Err();
The server returned a non-2xx HTTP response code.
Not that this error is only used by certain APIs that interpret the HTTP response itself. URLRequest for instance just passes most non-2xx response back as success.
HttpResponseCodeFailureError
-379
HTTP_RESPONSE_CODE_FAILURE
const err = new chromiumNetErrors.HttpResponseCodeFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-379);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('HTTP_RESPONSE_CODE_FAILURE');
const err = new Err();
The certificate presented on a QUIC connection does not chain to a known root and the origin connected to is not on a list of domains where unknown roots are allowed.
QuicCertRootNotKnownError
-380
QUIC_CERT_ROOT_NOT_KNOWN
const err = new chromiumNetErrors.QuicCertRootNotKnownError();
// or
const Err = chromiumNetErrors.getErrorByCode(-380);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('QUIC_CERT_ROOT_NOT_KNOWN');
const err = new Err();
A GOAWAY frame has been received indicating that the request has not been processed and is therefore safe to retry on a different connection.
QuicGoawayRequestCanBeRetriedError
-381
QUIC_GOAWAY_REQUEST_CAN_BE_RETRIED
const err = new chromiumNetErrors.QuicGoawayRequestCanBeRetriedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-381);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('QUIC_GOAWAY_REQUEST_CAN_BE_RETRIED');
const err = new Err();
The cache does not have the requested entry.
CacheMissError
-400
CACHE_MISS
const err = new chromiumNetErrors.CacheMissError();
// or
const Err = chromiumNetErrors.getErrorByCode(-400);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_MISS');
const err = new Err();
Unable to read from the disk cache.
CacheReadFailureError
-401
CACHE_READ_FAILURE
const err = new chromiumNetErrors.CacheReadFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-401);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_READ_FAILURE');
const err = new Err();
Unable to write to the disk cache.
CacheWriteFailureError
-402
CACHE_WRITE_FAILURE
const err = new chromiumNetErrors.CacheWriteFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-402);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_WRITE_FAILURE');
const err = new Err();
The operation is not supported for this entry.
CacheOperationNotSupportedError
-403
CACHE_OPERATION_NOT_SUPPORTED
const err = new chromiumNetErrors.CacheOperationNotSupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-403);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_OPERATION_NOT_SUPPORTED');
const err = new Err();
The disk cache is unable to open this entry.
CacheOpenFailureError
-404
CACHE_OPEN_FAILURE
const err = new chromiumNetErrors.CacheOpenFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-404);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_OPEN_FAILURE');
const err = new Err();
The disk cache is unable to create this entry.
CacheCreateFailureError
-405
CACHE_CREATE_FAILURE
const err = new chromiumNetErrors.CacheCreateFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-405);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_CREATE_FAILURE');
const err = new Err();
Multiple transactions are racing to create disk cache entries. This is an internal error returned from the HttpCache to the HttpCacheTransaction that tells the transaction to restart the entry-creation logic because the state of the cache has changed.
CacheRaceError
-406
CACHE_RACE
const err = new chromiumNetErrors.CacheRaceError();
// or
const Err = chromiumNetErrors.getErrorByCode(-406);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_RACE');
const err = new Err();
The cache was unable to read a checksum record on an entry. This can be returned from attempts to read from the cache. It is an internal error, returned by the SimpleCache backend, but not by any URLRequest methods or members.
CacheChecksumReadFailureError
-407
CACHE_CHECKSUM_READ_FAILURE
const err = new chromiumNetErrors.CacheChecksumReadFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-407);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_CHECKSUM_READ_FAILURE');
const err = new Err();
The cache found an entry with an invalid checksum. This can be returned from attempts to read from the cache. It is an internal error, returned by the SimpleCache backend, but not by any URLRequest methods or members.
CacheChecksumMismatchError
-408
CACHE_CHECKSUM_MISMATCH
const err = new chromiumNetErrors.CacheChecksumMismatchError();
// or
const Err = chromiumNetErrors.getErrorByCode(-408);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_CHECKSUM_MISMATCH');
const err = new Err();
Internal error code for the HTTP cache. The cache lock timeout has fired.
CacheLockTimeoutError
-409
CACHE_LOCK_TIMEOUT
const err = new chromiumNetErrors.CacheLockTimeoutError();
// or
const Err = chromiumNetErrors.getErrorByCode(-409);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_LOCK_TIMEOUT');
const err = new Err();
Received a challenge after the transaction has read some data, and the credentials aren't available. There isn't a way to get them at that point.
CacheAuthFailureAfterReadError
-410
CACHE_AUTH_FAILURE_AFTER_READ
const err = new chromiumNetErrors.CacheAuthFailureAfterReadError();
// or
const Err = chromiumNetErrors.getErrorByCode(-410);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_AUTH_FAILURE_AFTER_READ');
const err = new Err();
Internal not-quite error code for the HTTP cache. In-memory hints suggest that the cache entry would not have been useable with the transaction's current configuration (e.g. load flags, mode, etc.)
CacheEntryNotSuitableError
-411
CACHE_ENTRY_NOT_SUITABLE
const err = new chromiumNetErrors.CacheEntryNotSuitableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-411);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_ENTRY_NOT_SUITABLE');
const err = new Err();
The disk cache is unable to doom this entry.
CacheDoomFailureError
-412
CACHE_DOOM_FAILURE
const err = new chromiumNetErrors.CacheDoomFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-412);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_DOOM_FAILURE');
const err = new Err();
The disk cache is unable to open or create this entry.
CacheOpenOrCreateFailureError
-413
CACHE_OPEN_OR_CREATE_FAILURE
const err = new chromiumNetErrors.CacheOpenOrCreateFailureError();
// or
const Err = chromiumNetErrors.getErrorByCode(-413);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CACHE_OPEN_OR_CREATE_FAILURE');
const err = new Err();
The server's response was insecure (e.g. there was a cert error).
InsecureResponseError
-501
INSECURE_RESPONSE
const err = new chromiumNetErrors.InsecureResponseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-501);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INSECURE_RESPONSE');
const err = new Err();
An attempt to import a client certificate failed, as the user's key database lacked a corresponding private key.
NoPrivateKeyForCertError
-502
NO_PRIVATE_KEY_FOR_CERT
const err = new chromiumNetErrors.NoPrivateKeyForCertError();
// or
const Err = chromiumNetErrors.getErrorByCode(-502);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('NO_PRIVATE_KEY_FOR_CERT');
const err = new Err();
An error adding a certificate to the OS certificate database.
AddUserCertFailedError
-503
ADD_USER_CERT_FAILED
const err = new chromiumNetErrors.AddUserCertFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-503);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('ADD_USER_CERT_FAILED');
const err = new Err();
An error occurred while handling a signed exchange.
InvalidSignedExchangeError
-504
INVALID_SIGNED_EXCHANGE
const err = new chromiumNetErrors.InvalidSignedExchangeError();
// or
const Err = chromiumNetErrors.getErrorByCode(-504);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_SIGNED_EXCHANGE');
const err = new Err();
An error occurred while handling a Web Bundle source.
InvalidWebBundleError
-505
INVALID_WEB_BUNDLE
const err = new chromiumNetErrors.InvalidWebBundleError();
// or
const Err = chromiumNetErrors.getErrorByCode(-505);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('INVALID_WEB_BUNDLE');
const err = new Err();
A Trust Tokens protocol operation-executing request failed for one of a number of reasons (precondition failure, internal error, bad response).
TrustTokenOperationFailedError
-506
TRUST_TOKEN_OPERATION_FAILED
const err = new chromiumNetErrors.TrustTokenOperationFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-506);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TRUST_TOKEN_OPERATION_FAILED');
const err = new Err();
When handling a Trust Tokens protocol operation-executing request, the system was able to execute the request's Trust Tokens operation without sending the request to its destination: for instance, the results could have been present in a local cache (for redemption) or the operation could have been diverted to a local provider (for "platform-provided" issuance).
TrustTokenOperationSuccessWithoutSendingRequestError
-507
TRUST_TOKEN_OPERATION_SUCCESS_WITHOUT_SENDING_REQUEST
const err = new chromiumNetErrors.TrustTokenOperationSuccessWithoutSendingRequestError();
// or
const Err = chromiumNetErrors.getErrorByCode(-507);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('TRUST_TOKEN_OPERATION_SUCCESS_WITHOUT_SENDING_REQUEST');
const err = new Err();
A generic error for failed FTP control connection command. If possible, please use or add a more specific error code.
FtpFailedError
-601
FTP_FAILED
const err = new chromiumNetErrors.FtpFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-601);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_FAILED');
const err = new Err();
The server cannot fulfill the request at this point. This is a temporary error. FTP response code 421.
FtpServiceUnavailableError
-602
FTP_SERVICE_UNAVAILABLE
const err = new chromiumNetErrors.FtpServiceUnavailableError();
// or
const Err = chromiumNetErrors.getErrorByCode(-602);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_SERVICE_UNAVAILABLE');
const err = new Err();
The server has aborted the transfer. FTP response code 426.
FtpTransferAbortedError
-603
FTP_TRANSFER_ABORTED
const err = new chromiumNetErrors.FtpTransferAbortedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-603);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_TRANSFER_ABORTED');
const err = new Err();
The file is busy, or some other temporary error condition on opening the file. FTP response code 450.
FtpFileBusyError
-604
FTP_FILE_BUSY
const err = new chromiumNetErrors.FtpFileBusyError();
// or
const Err = chromiumNetErrors.getErrorByCode(-604);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_FILE_BUSY');
const err = new Err();
Server rejected our command because of syntax errors. FTP response codes 500, 501.
FtpSyntaxError
-605
FTP_SYNTAX_ERROR
const err = new chromiumNetErrors.FtpSyntaxError();
// or
const Err = chromiumNetErrors.getErrorByCode(-605);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_SYNTAX_ERROR');
const err = new Err();
Server does not support the command we issued. FTP response codes 502, 504.
FtpCommandNotSupportedError
-606
FTP_COMMAND_NOT_SUPPORTED
const err = new chromiumNetErrors.FtpCommandNotSupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-606);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_COMMAND_NOT_SUPPORTED');
const err = new Err();
Server rejected our command because we didn't issue the commands in right order. FTP response code 503.
FtpBadCommandSequenceError
-607
FTP_BAD_COMMAND_SEQUENCE
const err = new chromiumNetErrors.FtpBadCommandSequenceError();
// or
const Err = chromiumNetErrors.getErrorByCode(-607);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('FTP_BAD_COMMAND_SEQUENCE');
const err = new Err();
PKCS #12 import failed due to incorrect password.
Pkcs12ImportBadPasswordError
-701
PKCS12_IMPORT_BAD_PASSWORD
const err = new chromiumNetErrors.Pkcs12ImportBadPasswordError();
// or
const Err = chromiumNetErrors.getErrorByCode(-701);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PKCS12_IMPORT_BAD_PASSWORD');
const err = new Err();
PKCS #12 import failed due to other error.
Pkcs12ImportFailedError
-702
PKCS12_IMPORT_FAILED
const err = new chromiumNetErrors.Pkcs12ImportFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-702);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PKCS12_IMPORT_FAILED');
const err = new Err();
CA import failed - not a CA cert.
ImportCaCertNotCaError
-703
IMPORT_CA_CERT_NOT_CA
const err = new chromiumNetErrors.ImportCaCertNotCaError();
// or
const Err = chromiumNetErrors.getErrorByCode(-703);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('IMPORT_CA_CERT_NOT_CA');
const err = new Err();
Import failed - certificate already exists in database. Note it's a little weird this is an error but reimporting a PKCS12 is ok (no-op). That's how Mozilla does it, though.
ImportCertAlreadyExistsError
-704
IMPORT_CERT_ALREADY_EXISTS
const err = new chromiumNetErrors.ImportCertAlreadyExistsError();
// or
const Err = chromiumNetErrors.getErrorByCode(-704);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('IMPORT_CERT_ALREADY_EXISTS');
const err = new Err();
CA import failed due to some other error.
ImportCaCertFailedError
-705
IMPORT_CA_CERT_FAILED
const err = new chromiumNetErrors.ImportCaCertFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-705);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('IMPORT_CA_CERT_FAILED');
const err = new Err();
Server certificate import failed due to some internal error.
ImportServerCertFailedError
-706
IMPORT_SERVER_CERT_FAILED
const err = new chromiumNetErrors.ImportServerCertFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-706);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('IMPORT_SERVER_CERT_FAILED');
const err = new Err();
PKCS #12 import failed due to invalid MAC.
Pkcs12ImportInvalidMacError
-707
PKCS12_IMPORT_INVALID_MAC
const err = new chromiumNetErrors.Pkcs12ImportInvalidMacError();
// or
const Err = chromiumNetErrors.getErrorByCode(-707);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PKCS12_IMPORT_INVALID_MAC');
const err = new Err();
PKCS #12 import failed due to invalid/corrupt file.
Pkcs12ImportInvalidFileError
-708
PKCS12_IMPORT_INVALID_FILE
const err = new chromiumNetErrors.Pkcs12ImportInvalidFileError();
// or
const Err = chromiumNetErrors.getErrorByCode(-708);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PKCS12_IMPORT_INVALID_FILE');
const err = new Err();
PKCS #12 import failed due to unsupported features.
Pkcs12ImportUnsupportedError
-709
PKCS12_IMPORT_UNSUPPORTED
const err = new chromiumNetErrors.Pkcs12ImportUnsupportedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-709);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PKCS12_IMPORT_UNSUPPORTED');
const err = new Err();
Key generation failed.
KeyGenerationFailedError
-710
KEY_GENERATION_FAILED
const err = new chromiumNetErrors.KeyGenerationFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-710);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('KEY_GENERATION_FAILED');
const err = new Err();
Failure to export private key.
PrivateKeyExportFailedError
-712
PRIVATE_KEY_EXPORT_FAILED
const err = new chromiumNetErrors.PrivateKeyExportFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-712);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('PRIVATE_KEY_EXPORT_FAILED');
const err = new Err();
Self-signed certificate generation failed.
SelfSignedCertGenerationFailedError
-713
SELF_SIGNED_CERT_GENERATION_FAILED
const err = new chromiumNetErrors.SelfSignedCertGenerationFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-713);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('SELF_SIGNED_CERT_GENERATION_FAILED');
const err = new Err();
The certificate database changed in some way.
CertDatabaseChangedError
-714
CERT_DATABASE_CHANGED
const err = new chromiumNetErrors.CertDatabaseChangedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-714);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('CERT_DATABASE_CHANGED');
const err = new Err();
DNS resolver received a malformed response.
DnsMalformedResponseError
-800
DNS_MALFORMED_RESPONSE
const err = new chromiumNetErrors.DnsMalformedResponseError();
// or
const Err = chromiumNetErrors.getErrorByCode(-800);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_MALFORMED_RESPONSE');
const err = new Err();
DNS server requires TCP
DnsServerRequiresTcpError
-801
DNS_SERVER_REQUIRES_TCP
const err = new chromiumNetErrors.DnsServerRequiresTcpError();
// or
const Err = chromiumNetErrors.getErrorByCode(-801);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_SERVER_REQUIRES_TCP');
const err = new Err();
DNS server failed. This error is returned for all of the following error conditions: 1 - Format error - The name server was unable to interpret the query. 2 - Server failure - The name server was unable to process this query due to a problem with the name server. 4 - Not Implemented - The name server does not support the requested kind of query. 5 - Refused - The name server refuses to perform the specified operation for policy reasons.
DnsServerFailedError
-802
DNS_SERVER_FAILED
const err = new chromiumNetErrors.DnsServerFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-802);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_SERVER_FAILED');
const err = new Err();
DNS transaction timed out.
DnsTimedOutError
-803
DNS_TIMED_OUT
const err = new chromiumNetErrors.DnsTimedOutError();
// or
const Err = chromiumNetErrors.getErrorByCode(-803);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_TIMED_OUT');
const err = new Err();
The entry was not found in cache or other local sources, for lookups where only local sources were queried. TODO(ericorth): Consider renaming to DNS_LOCAL_MISS or something like that as the cache is not necessarily queried either.
DnsCacheMissError
-804
DNS_CACHE_MISS
const err = new chromiumNetErrors.DnsCacheMissError();
// or
const Err = chromiumNetErrors.getErrorByCode(-804);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_CACHE_MISS');
const err = new Err();
Suffix search list rules prevent resolution of the given host name.
DnsSearchEmptyError
-805
DNS_SEARCH_EMPTY
const err = new chromiumNetErrors.DnsSearchEmptyError();
// or
const Err = chromiumNetErrors.getErrorByCode(-805);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_SEARCH_EMPTY');
const err = new Err();
Failed to sort addresses according to RFC3484.
DnsSortError
-806
DNS_SORT_ERROR
const err = new chromiumNetErrors.DnsSortError();
// or
const Err = chromiumNetErrors.getErrorByCode(-806);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_SORT_ERROR');
const err = new Err();
Failed to resolve the hostname of a DNS-over-HTTPS server.
DnsSecureResolverHostnameResolutionFailedError
-808
DNS_SECURE_RESOLVER_HOSTNAME_RESOLUTION_FAILED
const err = new chromiumNetErrors.DnsSecureResolverHostnameResolutionFailedError();
// or
const Err = chromiumNetErrors.getErrorByCode(-808);
const err = new Err();
// or
const Err = chromiumNetErrors.getErrorByDescription('DNS_SECURE_RESOLVER_HOSTNAME_RESOLUTION_FAILED');
const err = new Err();
Author: Maxkueng
Source Code: https://github.com/maxkueng/chromium-net-errors
License: MIT license
1669099573
In this article, we will know what is face recognition and how is different from face detection. We will go briefly over the theory of face recognition and then jump on to the coding section. At the end of this article, you will be able to make a face recognition program for recognizing faces in images as well as on a live webcam feed.
In computer vision, one essential problem we are trying to figure out is to automatically detect objects in an image without human intervention. Face detection can be thought of as such a problem where we detect human faces in an image. There may be slight differences in the faces of humans but overall, it is safe to say that there are certain features that are associated with all the human faces. There are various face detection algorithms but Viola-Jones Algorithm is one of the oldest methods that is also used today and we will use the same later in the article. You can go through the Viola-Jones Algorithm after completing this article as I’ll link it at the end of this article.
Face detection is usually the first step towards many face-related technologies, such as face recognition or verification. However, face detection can have very useful applications. The most successful application of face detection would probably be photo taking. When you take a photo of your friends, the face detection algorithm built into your digital camera detects where the faces are and adjusts the focus accordingly.
For a tutorial on Real-Time Face detection
Now that we are successful in making such algorithms that can detect faces, can we also recognise whose faces are they?
Face recognition is a method of identifying or verifying the identity of an individual using their face. There are various algorithms that can do face recognition but their accuracy might vary. Here I am going to describe how we do face recognition using deep learning.
So now let us understand how we recognise faces using deep learning. We make use of face embedding in which each face is converted into a vector and this technique is called deep metric learning. Let me further divide this process into three simple steps for easy understanding:
Face Detection: The very first task we perform is detecting faces in the image or video stream. Now that we know the exact location/coordinates of face, we extract this face for further processing ahead.
Feature Extraction: Now that we have cropped the face out of the image, we extract features from it. Here we are going to use face embeddings to extract the features out of the face. A neural network takes an image of the person’s face as input and outputs a vector which represents the most important features of a face. In machine learning, this vector is called embedding and thus we call this vector as face embedding. Now how does this help in recognizing faces of different persons?
While training the neural network, the network learns to output similar vectors for faces that look similar. For example, if I have multiple images of faces within different timespan, of course, some of the features of my face might change but not up to much extent. So in this case the vectors associated with the faces are similar or in short, they are very close in the vector space. Take a look at the below diagram for a rough idea:
Now after training the network, the network learns to output vectors that are closer to each other(similar) for faces of the same person(looking similar). The above vectors now transform into:
We are not going to train such a network here as it takes a significant amount of data and computation power to train such networks. We will use a pre-trained network trained by Davis King on a dataset of ~3 million images. The network outputs a vector of 128 numbers which represent the most important features of a face.
Now that we know how this network works, let us see how we use this network on our own data. We pass all the images in our data to this pre-trained network to get the respective embeddings and save these embeddings in a file for the next step.
Comparing faces: Now that we have face embeddings for every face in our data saved in a file, the next step is to recognise a new t image that is not in our data. So the first step is to compute the face embedding for the image using the same network we used above and then compare this embedding with the rest of the embeddings we have. We recognise the face if the generated embedding is closer or similar to any other embedding as shown below:
So we passed two images, one of the images is of Vladimir Putin and other of George W. Bush. In our example above, we did not save the embeddings for Putin but we saved the embeddings of Bush. Thus when we compared the two new embeddings with the existing ones, the vector for Bush is closer to the other face embeddings of Bush whereas the face embeddings of Putin are not closer to any other embedding and thus the program cannot recognise him.
In the field of Artificial Intelligence, Computer Vision is one of the most interesting and Challenging tasks. Computer Vision acts like a bridge between Computer Software and visualizations around us. It allows computer software to understand and learn about the visualizations in the surroundings. For Example: Based on the color, shape and size determining the fruit. This task can be very easy for the human brain however in the Computer Vision pipeline, first we gather the data, then we perform the data processing activities and then we train and teach the model to understand how to distinguish between the fruits based on size, shape and color of fruit.
Currently, various packages are present to perform machine learning, deep learning and computer vision tasks. By far, computer vision is the best module for such complex activities. OpenCV is an open-source library. It is supported by various programming languages such as R, Python. It runs on most of the platforms such as Windows, Linux and MacOS.
To know more about how face recognition works on opencv, check out the free course on face recognition in opencv.
Advantages of OpenCV:
Installation:
Here we will be focusing on installing OpenCV for python only. We can install OpenCV using pip or conda(for anaconda environment).
Using pip, the installation process of openCV can be done by using the following command in the command prompt.
pip install opencv-python
If you are using anaconda environment, either you can execute the above code in anaconda prompt or you can execute the following code in anaconda prompt.
conda install -c conda-forge opencv
In this section, we shall implement face recognition using OpenCV and Python. First, let us see the libraries we will need and how to install them:
OpenCV is an image and video processing library and is used for image and video analysis, like facial detection, license plate reading, photo editing, advanced robotic vision, optical character recognition, and a whole lot more.
The dlib library, maintained by Davis King, contains our implementation of “deep metric learning” which is used to construct our face embeddings used for the actual recognition process.
The face_recognition library, created by Adam Geitgey, wraps around dlib’s facial recognition functionality, and this library is super easy to work with and we will be using this in our code. Remember to install dlib library first before you install face_recognition.
To install OpenCV, type in command prompt
pip install opencv-python |
I have tried various ways to install dlib on Windows but the easiest of all of them is via Anaconda. First, install Anaconda (here is a guide to install it) and then use this command in your command prompt:
conda install -c conda-forge dlib |
Next to install face_recognition, type in command prompt
pip install face_recognition |
Now that we have all the dependencies installed, let us start coding. We will have to create three files, one will take our dataset and extract face embedding for each face using dlib. Next, we will save these embedding in a file.
In the next file we will compare the faces with the existing the recognise faces in images and next we will do the same but recognise faces in live webcam feed
First, you need to get a dataset or even create one of you own. Just make sure to arrange all images in folders with each folder containing images of just one person.
Next, save the dataset in a folder the same as you are going to make the file. Now here is the code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
|
Now that we have stored the embedding in a file named “face_enc”, we can use them to recognise faces in images or live video stream.
Here is the script to recognise faces on a live webcam feed:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 |
|
https://www.youtube.com/watch?v=fLnGdkZxRkg
Although in the example above we have used haar cascade to detect faces, you can also use face_recognition.face_locations to detect a face as we did in the previous script
The script for detecting and recognising faces in images is almost similar to what you saw above. Try it yourself and if you can’t take a look at the code below:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
|
Output:
InputOutput
This brings us to the end of this article where we learned about face recognition.
You can also upskill with Great Learning’s PGP Artificial Intelligence and Machine Learning Course. The course offers mentorship from industry leaders, and you will also have the opportunity to work on real-time industry-relevant projects.
Original article source at: https://www.mygreatlearning.com
1600481520
Javascript array find() is an inbuilt js function that returns the value of the first item in the Array that satisfies a provided testing function. Otherwise, undefined will be returned. The array find() method returns the value of the first element in an array that passes a test of provided function.
If an Array find() method finds an item where the function returns a true value. Javascript find() returns the value of that array item immediately and does not check the remaining values of that Array.
Javascript Array.find() is the inbuilt function that is used to get a value of the first item in the Array that meets the provided condition. If you need an index of the found item in the Array, use the findIndex(). If you need to find an index of the value, use Array .prototype.indexOf(). If you need to find if the value exists in an array, use Array .prototype.includes().
It checks all the items of the Array, and whichever the first item meets, the condition is going to print. If more than one item meets the condition, then the first item satisfying the requirement is returned. Suppose that you want to find the first odd number in the Array. The argument function checks whether an argument passed to it is an odd number or not.
Javascript find() function calls an argument function for every item of the Array. The first odd number for which argument function returns true is reported by the find() function as the answer.
#javascript #javascript find #array.find