1
0
mirror of https://github.com/v2fly/v2ray-core.git synced 2024-09-09 05:26:39 -04:00

refactor error messages

This commit is contained in:
Darien Raymond 2017-04-09 01:43:25 +02:00
parent 8175a751db
commit 35248497d2
No known key found for this signature in database
GPG Key ID: 7251FFA14BB18169
141 changed files with 710 additions and 481 deletions

3
app/app.go Normal file
View File

@ -0,0 +1,3 @@
package app
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg app -path App

View File

@ -1,5 +1,7 @@
package impl
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg impl -path App,Dispatcher,Default
import (
"context"
@ -9,7 +11,6 @@ import (
"v2ray.com/core/app/proxyman"
"v2ray.com/core/app/router"
"v2ray.com/core/common"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/net"
"v2ray.com/core/proxy"
"v2ray.com/core/transport/ray"
@ -23,13 +24,13 @@ type DefaultDispatcher struct {
func NewDefaultDispatcher(ctx context.Context, config *dispatcher.Config) (*DefaultDispatcher, error) {
space := app.SpaceFromContext(ctx)
if space == nil {
return nil, errors.New("no space in context").Path("App", "Dispatcher", "Default")
return nil, newError("no space in context")
}
d := &DefaultDispatcher{}
space.OnInitialize(func() error {
d.ohm = proxyman.OutboundHandlerManagerFromSpace(space)
if d.ohm == nil {
return errors.New("OutboundHandlerManager is not found in the space").Path("App", "Dispatcher", "Default")
return newError("OutboundHandlerManager is not found in the space")
}
d.router = router.FromSpace(space)
return nil
@ -58,13 +59,13 @@ func (v *DefaultDispatcher) Dispatch(ctx context.Context, destination net.Destin
if v.router != nil {
if tag, err := v.router.TakeDetour(ctx); err == nil {
if handler := v.ohm.GetHandler(tag); handler != nil {
log.Trace(errors.New("taking detour [", tag, "] for [", destination, "]").Path("App", "Dispatcher", "Default"))
log.Trace(newError("taking detour [", tag, "] for [", destination, "]"))
dispatcher = handler
} else {
log.Trace(errors.New("nonexisting tag: ", tag).AtWarning().Path("App", "Dispatcher", "Default"))
log.Trace(newError("nonexisting tag: ", tag).AtWarning())
}
} else {
log.Trace(errors.New("default route for ", destination).Path("App", "Dispatcher", "Default"))
log.Trace(newError("default route for ", destination))
}
}

View File

@ -0,0 +1,7 @@
package impl
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).Path("App", "Dispatcher", "Default")
}

View File

@ -4,7 +4,6 @@ import (
"net"
"v2ray.com/core/app/log"
"v2ray.com/core/common/errors"
)
func (v *Config) GetInternalHosts() map[string]net.IP {
@ -12,7 +11,7 @@ func (v *Config) GetInternalHosts() map[string]net.IP {
for domain, ipOrDomain := range v.GetHosts() {
address := ipOrDomain.AsAddress()
if address.Family().IsDomain() {
log.Trace(errors.New("ignoring domain address in static hosts: ", address.Domain()).AtWarning().Path("App", "DNS", "Config"))
log.Trace(newError("ignoring domain address in static hosts: ", address.Domain()).AtWarning())
continue
}
hosts[domain] = address.IP()

View File

@ -1,5 +1,7 @@
package dns
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg dns -path App,DNS
import (
"net"

View File

@ -0,0 +1,5 @@
package dns
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error { return errors.New(values...).Path("App", "DNS") }

View File

@ -0,0 +1,7 @@
package server
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).Path("App", "DNS", "Server")
}

View File

@ -11,7 +11,6 @@ import (
"v2ray.com/core/app/log"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/dice"
"v2ray.com/core/common/errors"
v2net "v2ray.com/core/common/net"
"v2ray.com/core/transport/internet/udp"
)
@ -89,7 +88,7 @@ func (v *UDPNameServer) AssignUnusedID(response chan<- *ARecord) uint16 {
if _, found := v.requests[id]; found {
continue
}
log.Trace(errors.New("add pending request id ", id).AtDebug().Path("App", "DNS", "UDPNameServer"))
log.Trace(newError("add pending request id ", id).AtDebug())
v.requests[id] = &PendingRequest{
expire: time.Now().Add(time.Second * 8),
response: response,
@ -105,7 +104,7 @@ func (v *UDPNameServer) HandleResponse(payload *buf.Buffer) {
msg := new(dns.Msg)
err := msg.Unpack(payload.Bytes())
if err != nil {
log.Trace(errors.New("failed to parse DNS response").Base(err).AtWarning().Path("App", "DNS", "UDPNameServer"))
log.Trace(newError("failed to parse DNS response").Base(err).AtWarning())
return
}
record := &ARecord{
@ -113,7 +112,7 @@ func (v *UDPNameServer) HandleResponse(payload *buf.Buffer) {
}
id := msg.Id
ttl := DefaultTTL
log.Trace(errors.New("handling response for id ", id, " content: ", msg.String()).AtDebug().Path("App", "DNS", "UDPNameServer"))
log.Trace(newError("handling response for id ", id, " content: ", msg.String()).AtDebug())
v.Lock()
request, found := v.requests[id]
@ -201,7 +200,7 @@ func (v *LocalNameServer) QueryA(domain string) <-chan *ARecord {
ips, err := net.LookupIP(domain)
if err != nil {
log.Trace(errors.New("failed to lookup IPs for domain ", domain).Path("App", "DNS", "LocalNameServer").Base(err))
log.Trace(newError("failed to lookup IPs for domain ", domain).Base(err))
return
}

View File

@ -1,5 +1,7 @@
package server
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg server -path App,DNS,Server
import (
"context"
"net"
@ -12,7 +14,6 @@ import (
"v2ray.com/core/app/dns"
"v2ray.com/core/app/log"
"v2ray.com/core/common"
"v2ray.com/core/common/errors"
v2net "v2ray.com/core/common/net"
)
@ -35,7 +36,7 @@ type CacheServer struct {
func NewCacheServer(ctx context.Context, config *dns.Config) (*CacheServer, error) {
space := app.SpaceFromContext(ctx)
if space == nil {
return nil, errors.New("no space in context").Path("App", "DNS", "CacheServer")
return nil, newError("no space in context")
}
server := &CacheServer{
records: make(map[string]*DomainRecord),
@ -45,7 +46,7 @@ func NewCacheServer(ctx context.Context, config *dns.Config) (*CacheServer, erro
space.OnInitialize(func() error {
disp := dispatcher.FromSpace(space)
if disp == nil {
return errors.New("dispatcher is not found in the space").Path("App", "DNS", "CacheServer")
return newError("dispatcher is not found in the space")
}
for idx, destPB := range config.NameServers {
address := destPB.Address.AsAddress()
@ -113,13 +114,13 @@ func (v *CacheServer) Get(domain string) []net.IP {
A: a,
}
v.Unlock()
log.Trace(errors.New("returning ", len(a.IPs), " IPs for domain ", domain).AtDebug().Path("App", "DNS", "CacheServer"))
log.Trace(newError("returning ", len(a.IPs), " IPs for domain ", domain).AtDebug())
return a.IPs
case <-time.After(QueryTimeout):
}
}
log.Trace(errors.New("returning nil for domain ", domain).AtDebug().Path("App", "DNS", "CacheServer"))
log.Trace(newError("returning nil for domain ", domain).AtDebug())
return nil
}

5
app/errors.generated.go Normal file
View File

@ -0,0 +1,5 @@
package app
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error { return errors.New(values...).Path("App") }

View File

@ -1,9 +1,6 @@
package log
import (
"v2ray.com/core/app/log/internal"
"v2ray.com/core/common/errors"
)
import "v2ray.com/core/app/log/internal"
// AccessStatus is the status of an access request from clients.
type AccessStatus string
@ -21,7 +18,7 @@ var (
func InitAccessLogger(file string) error {
logger, err := internal.NewFileLogWriter(file)
if err != nil {
return errors.New("failed to create access logger on file: ", file).Base(err).Path("App", "Log")
return newError("failed to create access logger on file: ", file).Base(err)
}
accessLoggerInstance = logger
return nil

View File

@ -0,0 +1,5 @@
package log
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error { return errors.New(values...).Path("App", "Log") }

View File

@ -1,5 +1,7 @@
package log
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg log -path App,Log
import (
"context"
@ -43,7 +45,7 @@ func SetLogLevel(level LogLevel) {
func InitErrorLogger(file string) error {
logger, err := internal.NewFileLogWriter(file)
if err != nil {
return errors.New("failed to create error logger on file (", file, ")").Base(err).Path("App", "Log")
return newError("failed to create error logger on file (", file, ")").Base(err)
}
streamLoggerInstance = logger
return nil

View File

@ -3,7 +3,6 @@ package proxyman
import (
"context"
"v2ray.com/core/common/errors"
"v2ray.com/core/proxy"
)
@ -23,7 +22,7 @@ func (s *AllocationStrategy) GetRefreshValue() uint32 {
func (c *OutboundHandlerConfig) GetProxyHandler(ctx context.Context) (proxy.Outbound, error) {
if c == nil {
return nil, errors.New("OutboundHandlerConfig is nil").Path("App", "Proxyman", "Outbound", "OutboundHandlerConfig")
return nil, newError("OutboundHandlerConfig is nil")
}
config, err := c.ProxySettings.GetInstance()
if err != nil {

View File

@ -0,0 +1,7 @@
package proxyman
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).Path("App", "Proxyman")
}

View File

@ -7,7 +7,6 @@ import (
"v2ray.com/core/app/proxyman"
"v2ray.com/core/app/proxyman/mux"
"v2ray.com/core/common/dice"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/net"
"v2ray.com/core/proxy"
)
@ -37,7 +36,7 @@ func NewAlwaysOnInboundHandler(ctx context.Context, tag string, receiverConfig *
}
for port := pr.From; port <= pr.To; port++ {
if nl.HasNetwork(net.Network_TCP) {
log.Trace(errors.New("creating tcp worker on ", address, ":", port).AtDebug().Path("App", "Proxyman", "Inbound", "AlwaysOnInboundHandler"))
log.Trace(newError("creating tcp worker on ", address, ":", port).AtDebug())
worker := &tcpWorker{
address: address,
port: net.Port(port),

View File

@ -9,7 +9,6 @@ import (
"v2ray.com/core/app/proxyman"
"v2ray.com/core/app/proxyman/mux"
"v2ray.com/core/common/dice"
"v2ray.com/core/common/errors"
v2net "v2ray.com/core/common/net"
"v2ray.com/core/proxy"
)
@ -93,7 +92,7 @@ func (h *DynamicInboundHandler) refresh() error {
port := h.allocatePort()
p, err := proxy.CreateInboundHandler(ctx, h.proxyConfig)
if err != nil {
log.Trace(errors.New("failed to create proxy instance").Base(err).Path("App", "Proxyman", "Inbound", "DynamicInboundHandler").AtWarning())
log.Trace(newError("failed to create proxy instance").Base(err).AtWarning())
continue
}
nl := p.Network()
@ -108,7 +107,7 @@ func (h *DynamicInboundHandler) refresh() error {
dispatcher: h.mux,
}
if err := worker.Start(); err != nil {
log.Trace(errors.New("failed to create TCP worker").Base(err).AtWarning().Path("App", "Proxyman", "Inbound", "DynamicInboundHandler"))
log.Trace(newError("failed to create TCP worker").Base(err).AtWarning())
continue
}
workers = append(workers, worker)
@ -124,7 +123,7 @@ func (h *DynamicInboundHandler) refresh() error {
dispatcher: h.mux,
}
if err := worker.Start(); err != nil {
log.Trace(errors.New("failed to create UDP worker").Base(err).AtWarning().Path("App", "Proxyman", "Inbound", "DynamicInboundHandler"))
log.Trace(newError("failed to create UDP worker").Base(err).AtWarning())
continue
}
workers = append(workers, worker)

View File

@ -0,0 +1,7 @@
package inbound
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).Path("App", "Proxyman", "Inbound")
}

View File

@ -1,11 +1,12 @@
package inbound
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg inbound -path App,Proxyman,Inbound
import (
"context"
"v2ray.com/core/app/proxyman"
"v2ray.com/core/common"
"v2ray.com/core/common/errors"
)
type DefaultInboundHandlerManager struct {
@ -26,7 +27,7 @@ func (m *DefaultInboundHandlerManager) AddHandler(ctx context.Context, config *p
}
receiverSettings, ok := rawReceiverSettings.(*proxyman.ReceiverConfig)
if !ok {
return errors.New("not a ReceiverConfig").Path("App", "Proxyman", "Inbound", "DefaultInboundHandlerManager")
return newError("not a ReceiverConfig")
}
proxySettings, err := config.ProxySettings.GetInstance()
if err != nil {
@ -50,7 +51,7 @@ func (m *DefaultInboundHandlerManager) AddHandler(ctx context.Context, config *p
}
if handler == nil {
return errors.New("unknown allocation strategy: ", receiverSettings.AllocationStrategy.Type).Path("App", "Proxyman", "Inbound", "DefaultInboundHandlerManager")
return newError("unknown allocation strategy: ", receiverSettings.AllocationStrategy.Type)
}
m.handlers = append(m.handlers, handler)
@ -63,7 +64,7 @@ func (m *DefaultInboundHandlerManager) AddHandler(ctx context.Context, config *p
func (m *DefaultInboundHandlerManager) GetHandler(ctx context.Context, tag string) (proxyman.InboundHandler, error) {
handler, found := m.taggedHandlers[tag]
if !found {
return nil, errors.New("handler not found: ", tag).Path("App", "Proxyman", "Inbound", "DefaultInboundHandlerManager")
return nil, newError("handler not found: ", tag)
}
return handler, nil
}

View File

@ -11,7 +11,6 @@ import (
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/app/log"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/errors"
v2net "v2ray.com/core/common/net"
"v2ray.com/core/proxy"
"v2ray.com/core/transport/internet"
@ -54,7 +53,7 @@ func (w *tcpWorker) callback(conn internet.Connection) {
ctx = proxy.ContextWithInboundEntryPoint(ctx, v2net.TCPDestination(w.address, w.port))
ctx = proxy.ContextWithSource(ctx, v2net.DestinationFromAddr(conn.RemoteAddr()))
if err := w.proxy.Process(ctx, v2net.Network_TCP, conn, w.dispatcher); err != nil {
log.Trace(errors.New("connection ends").Base(err).Path("App", "Proxyman", "Inbound", "TCPWorker"))
log.Trace(newError("connection ends").Base(err))
}
cancel()
conn.Close()
@ -231,7 +230,7 @@ func (w *udpWorker) callback(b *buf.Buffer, source v2net.Destination, originalDe
ctx = proxy.ContextWithSource(ctx, source)
ctx = proxy.ContextWithInboundEntryPoint(ctx, v2net.UDPDestination(w.address, w.port))
if err := w.proxy.Process(ctx, v2net.Network_UDP, conn, w.dispatcher); err != nil {
log.Trace(errors.New("connection ends").Base(err).Path("App", "Proxymann", "Inbound", "UDPWorker"))
log.Trace(newError("connection ends").Base(err))
}
w.removeConn(source)
cancel()

View File

@ -0,0 +1,7 @@
package mux
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).Path("App", "Proxyman", "Mux")
}

View File

@ -2,7 +2,6 @@ package mux
import (
"v2ray.com/core/common/buf"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/net"
"v2ray.com/core/common/serial"
)
@ -114,7 +113,7 @@ func (f FrameMetadata) AsSupplier() buf.Supplier {
func ReadFrameFrom(b []byte) (*FrameMetadata, error) {
if len(b) < 4 {
return nil, errors.New("insufficient buffer: ", len(b)).Path("App", "Proxyman", "Mux", "Frame")
return nil, newError("insufficient buffer: ", len(b))
}
f := &FrameMetadata{
@ -144,7 +143,7 @@ func ReadFrameFrom(b []byte) (*FrameMetadata, error) {
addr = net.DomainAddress(string(b[1 : 1+nDomain]))
b = b[nDomain+1:]
default:
return nil, errors.New("unknown address type: ", addrType).Path("App", "Proxyman", "Mux", "Frame")
return nil, newError("unknown address type: ", addrType)
}
switch network {
case TargetNetworkTCP:
@ -152,7 +151,7 @@ func ReadFrameFrom(b []byte) (*FrameMetadata, error) {
case TargetNetworkUDP:
f.Target = net.UDPDestination(addr, port)
default:
return nil, errors.New("unknown network type: ", network).Path("App", "Proxyman", "Mux", "Frame")
return nil, newError("unknown network type: ", network)
}
}

View File

@ -1,5 +1,7 @@
package mux
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg mux -path App,Proxyman,Mux
import (
"context"
"sync"
@ -9,7 +11,6 @@ import (
"v2ray.com/core/app/dispatcher"
"v2ray.com/core/app/log"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/net"
"v2ray.com/core/common/signal"
"v2ray.com/core/proxy"
@ -83,7 +84,7 @@ func (m *ClientManager) Dispatch(ctx context.Context, outboundRay ray.OutboundRa
client, err := NewClient(m.proxy, m.dialer, m)
if err != nil {
return errors.New("failed to create client").Base(err).Path("App", "Proxyman", "Mux", "ClientManager")
return newError("failed to create client").Base(err)
}
m.clients = append(m.clients, client)
client.Dispatch(ctx, outboundRay)
@ -200,16 +201,16 @@ func fetchInput(ctx context.Context, s *session, output buf.Writer) {
defer writer.Close()
defer s.closeUplink()
log.Trace(errors.New("dispatching request to ", dest).Path("Proxyman", "Mux", "Client"))
log.Trace(newError("dispatching request to ", dest))
data, _ := s.input.ReadTimeout(time.Millisecond * 500)
if data != nil {
if err := writer.Write(data); err != nil {
log.Trace(errors.New("failed to write first payload").Base(err).Path("Proxyman", "Mux", "Client"))
log.Trace(newError("failed to write first payload").Base(err))
return
}
}
if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
log.Trace(errors.New("failed to fetch all input").Base(err).Path("Proxyman", "Mux", "Client"))
log.Trace(newError("failed to fetch all input").Base(err))
}
}
@ -287,7 +288,7 @@ func (m *Client) fetchOutput() {
for {
meta, err := reader.ReadMetadata()
if err != nil {
log.Trace(errors.New("failed to read metadata").Base(err).Path("Proxyman", "Mux", "Client"))
log.Trace(newError("failed to read metadata").Base(err))
break
}
m.access.RLock()
@ -308,7 +309,7 @@ func (m *Client) fetchOutput() {
}
if err != nil {
log.Trace(errors.New("failed to read data").Base(err).Path("Proxyman", "Mux", "Client"))
log.Trace(newError("failed to read data").Base(err))
break
}
}
@ -324,7 +325,7 @@ func NewServer(ctx context.Context) *Server {
space.OnInitialize(func() error {
d := dispatcher.FromSpace(space)
if d == nil {
return errors.New("no dispatcher in space").Path("Proxyman", "Mux", "Server")
return newError("no dispatcher in space")
}
s.dispatcher = d
return nil
@ -363,7 +364,7 @@ func (w *ServerWorker) remove(id uint16) {
func handle(ctx context.Context, s *session, output buf.Writer) {
writer := NewResponseWriter(s.id, output)
if err := buf.PipeUntilEOF(signal.BackgroundTimer(), s.input, writer); err != nil {
log.Trace(errors.New("session ", s.id, " ends: ").Base(err).Path("Proxyman", "Mux", "ServerWorker"))
log.Trace(newError("session ", s.id, " ends: ").Base(err))
}
writer.Close()
s.closeDownlink()
@ -381,7 +382,7 @@ func (w *ServerWorker) run(ctx context.Context) {
meta, err := reader.ReadMetadata()
if err != nil {
log.Trace(errors.New("failed to read metadata").Base(err).Path("Proxyman", "Mux", "ServerWorker"))
log.Trace(newError("failed to read metadata").Base(err))
return
}
@ -395,10 +396,10 @@ func (w *ServerWorker) run(ctx context.Context) {
}
if meta.SessionStatus == SessionStatusNew {
log.Trace(errors.New("received request for ", meta.Target).Path("Proxyman", "Mux", "ServerWorker"))
log.Trace(newError("received request for ", meta.Target))
inboundRay, err := w.dispatcher.Dispatch(ctx, meta.Target)
if err != nil {
log.Trace(errors.New("failed to dispatch request.").Base(err).Path("Proxymann", "Mux", "ServerWorker"))
log.Trace(newError("failed to dispatch request.").Base(err))
continue
}
s = &session{
@ -424,7 +425,7 @@ func (w *ServerWorker) run(ctx context.Context) {
}
if err != nil {
log.Trace(errors.New("failed to read data").Base(err).Path("Proxymann", "Mux", "ServerWorker"))
log.Trace(newError("failed to read data").Base(err))
break
}
}

View File

@ -4,7 +4,6 @@ import (
"io"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/serial"
)
@ -30,7 +29,7 @@ func (r *Reader) ReadMetadata() (*FrameMetadata, error) {
}
metaLen := serial.BytesToUint16(b.Bytes())
if metaLen > 512 {
return nil, errors.New("invalid metalen ", metaLen).Path("App", "Proxyman", "Mux", "Reader")
return nil, newError("invalid metalen ", metaLen)
}
b.Clear()
if err := b.AppendSupplier(buf.ReadFullFrom(r.reader, int(metaLen))); err != nil {

View File

@ -0,0 +1,7 @@
package outbound
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error {
return errors.New(values...).Path("App", "Proxyman", "Outbound")
}

View File

@ -32,12 +32,12 @@ func NewHandler(ctx context.Context, config *proxyman.OutboundHandlerConfig) (*H
}
space := app.SpaceFromContext(ctx)
if space == nil {
return nil, errors.New("no space in context").Path("App", "Proxyman", "Outbound", "Handler")
return nil, newError("no space in context")
}
space.OnInitialize(func() error {
ohm := proxyman.OutboundHandlerManagerFromSpace(space)
if ohm == nil {
return errors.New("no OutboundManager in space").Path("App", "Proxyman", "Outbound", "Handler")
return newError("no OutboundManager in space")
}
h.outboundManager = ohm
return nil
@ -52,7 +52,7 @@ func NewHandler(ctx context.Context, config *proxyman.OutboundHandlerConfig) (*H
case *proxyman.SenderConfig:
h.senderSettings = s
default:
return nil, errors.New("settings is not SenderConfig").Path("App", "Proxyman", "Outbound", "Handler")
return nil, newError("settings is not SenderConfig")
}
}
@ -73,13 +73,13 @@ func (h *Handler) Dispatch(ctx context.Context, outboundRay ray.OutboundRay) {
if h.mux != nil {
err := h.mux.Dispatch(ctx, outboundRay)
if err != nil {
log.Trace(errors.New("failed to process outbound traffic").Base(err).Path("App", "Proxyman", "Outbound", "Handler"))
log.Trace(newError("failed to process outbound traffic").Base(err))
}
} else {
err := h.proxy.Process(ctx, outboundRay, h)
// Ensure outbound ray is properly closed.
if err != nil && errors.Cause(err) != io.EOF {
log.Trace(errors.New("failed to process outbound traffic").Base(err).Path("App", "Proxyman", "Outbound", "Handler"))
log.Trace(newError("failed to process outbound traffic").Base(err))
outboundRay.OutboundOutput().CloseError()
} else {
outboundRay.OutboundOutput().Close()
@ -95,14 +95,14 @@ func (h *Handler) Dial(ctx context.Context, dest v2net.Destination) (internet.Co
tag := h.senderSettings.ProxySettings.Tag
handler := h.outboundManager.GetHandler(tag)
if handler != nil {
log.Trace(errors.New("proxying to ", tag).AtDebug().Path("App", "Proxyman", "Outbound", "Handler"))
log.Trace(newError("proxying to ", tag).AtDebug())
ctx = proxy.ContextWithTarget(ctx, dest)
stream := ray.NewRay(ctx)
go handler.Dispatch(ctx, stream)
return NewConnection(stream), nil
}
log.Trace(errors.New("failed to get outbound handler with tag: ", tag).AtWarning().Path("App", "Proxyman", "Outbound", "Handler"))
log.Trace(newError("failed to get outbound handler with tag: ", tag).AtWarning())
}
if h.senderSettings.Via != nil {

View File

@ -1,5 +1,7 @@
package outbound
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg outbound -path App,Proxyman,Outbound
import (
"context"
"sync"

View File

@ -1,6 +1,8 @@
// Package proxyman defines applications for manageing inbound and outbound proxies.
package proxyman
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg proxyman -path App,Proxyman
import (
"context"

View File

@ -4,7 +4,6 @@ import (
"context"
"net"
"v2ray.com/core/common/errors"
v2net "v2ray.com/core/common/net"
)
@ -53,7 +52,7 @@ func (v *RoutingRule) BuildCondition() (Condition, error) {
}
ipv6Cond.Add(matcher)
default:
return nil, errors.New("Router: Invalid IP length.")
return nil, newError("Router: Invalid IP length.")
}
}
@ -94,7 +93,7 @@ func (v *RoutingRule) BuildCondition() (Condition, error) {
}
ipv6Cond.Add(matcher)
default:
return nil, errors.New("Router: Invalid IP length.")
return nil, newError("Router: Invalid IP length.")
}
}
@ -119,7 +118,7 @@ func (v *RoutingRule) BuildCondition() (Condition, error) {
}
if conds.Len() == 0 {
return nil, errors.New("Router: This rule has no effective fields.")
return nil, newError("Router: This rule has no effective fields.")
}
return conds, nil

View File

@ -0,0 +1,5 @@
package router
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error { return errors.New(values...).Path("App", "Router") }

View File

@ -1,5 +1,7 @@
package router
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg router -path App,Router
import (
"context"
@ -7,13 +9,12 @@ import (
"v2ray.com/core/app/dns"
"v2ray.com/core/app/log"
"v2ray.com/core/common"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/net"
"v2ray.com/core/proxy"
)
var (
ErrNoRuleApplicable = errors.New("No rule applicable")
ErrNoRuleApplicable = newError("No rule applicable")
)
type Router struct {
@ -25,7 +26,7 @@ type Router struct {
func NewRouter(ctx context.Context, config *Config) (*Router, error) {
space := app.SpaceFromContext(ctx)
if space == nil {
return nil, errors.New("Router: No space in context.")
return nil, newError("Router: No space in context.")
}
r := &Router{
domainStrategy: config.DomainStrategy,
@ -44,7 +45,7 @@ func NewRouter(ctx context.Context, config *Config) (*Router, error) {
r.dnsServer = dns.FromSpace(space)
if r.dnsServer == nil {
return errors.New("Router: DNS is not found in the space.")
return newError("Router: DNS is not found in the space.")
}
return nil
})
@ -76,7 +77,7 @@ func (v *Router) TakeDetour(ctx context.Context) (string, error) {
}
if v.domainStrategy == Config_IpIfNonMatch && dest.Address.Family().IsDomain() {
log.Trace(errors.New("looking up IP for ", dest).Path("App", "Router"))
log.Trace(newError("looking up IP for ", dest))
ipDests := v.resolveIP(dest)
if ipDests != nil {
ctx = proxy.ContextWithResolveIPs(ctx, ipDests)

View File

@ -5,7 +5,6 @@ import (
"reflect"
"v2ray.com/core/common"
"v2ray.com/core/common/errors"
)
type Application interface {
@ -25,7 +24,7 @@ func CreateAppFromConfig(ctx context.Context, config interface{}) (Application,
case Application:
return a, nil
default:
return nil, errors.New("App: Not an application.")
return nil, newError("App: Not an application.")
}
}
@ -82,7 +81,7 @@ func (v *spaceImpl) GetApplication(appInterface interface{}) Application {
func (v *spaceImpl) AddApplication(app Application) error {
if v == nil {
return errors.New("App: Nil space.")
return newError("App: Nil space.")
}
appType := reflect.TypeOf(app.Interface())
v.cache[appType] = app
@ -113,7 +112,7 @@ const (
func AddApplicationToSpace(ctx context.Context, appConfig interface{}) error {
space := SpaceFromContext(ctx)
if space == nil {
return errors.New("App: No space in context.")
return newError("App: No space in context.")
}
application, err := CreateAppFromConfig(ctx, appConfig)
if err != nil {

3
common/buf/buf.go Normal file
View File

@ -0,0 +1,3 @@
package buf
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg buf -path Buf

View File

@ -0,0 +1,5 @@
package buf
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error { return errors.New(values...).Path("Buf") }

View File

@ -14,7 +14,7 @@ type Reader interface {
Read() (*Buffer, error)
}
var ErrReadTimeout = errors.New("Buf: IO timeout.")
var ErrReadTimeout = newError("Buf: IO timeout.")
type TimeoutReader interface {
ReadTimeout(time.Duration) (*Buffer, error)

View File

@ -2,6 +2,8 @@
// See each sub-package for detail.
package common
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg common -path Common
// Must panics if err is not nil.
func Must(err error) {
if err != nil {

View File

@ -8,12 +8,11 @@ import (
"v2ray.com/core/common"
"v2ray.com/core/common/buf"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/serial"
)
var (
errInsufficientBuffer = errors.New("insufficient buffer")
errInsufficientBuffer = newError("insufficient buffer")
)
type BytesGenerator interface {
@ -52,7 +51,7 @@ type AEADAuthenticator struct {
func (v *AEADAuthenticator) Open(dst, cipherText []byte) ([]byte, error) {
iv := v.NonceGenerator.Next()
if len(iv) != v.AEAD.NonceSize() {
return nil, errors.New("Crypto:AEADAuthenticator: Invalid nonce size: ", len(iv))
return nil, newError("Crypto:AEADAuthenticator: Invalid nonce size: ", len(iv))
}
additionalData := v.AdditionalDataGenerator.Next()
@ -62,7 +61,7 @@ func (v *AEADAuthenticator) Open(dst, cipherText []byte) ([]byte, error) {
func (v *AEADAuthenticator) Seal(dst, plainText []byte) ([]byte, error) {
iv := v.NonceGenerator.Next()
if len(iv) != v.AEAD.NonceSize() {
return nil, errors.New("Crypto:AEADAuthenticator: Invalid nonce size: ", len(iv))
return nil, newError("Crypto:AEADAuthenticator: Invalid nonce size: ", len(iv))
}
additionalData := v.AdditionalDataGenerator.Next()
@ -128,13 +127,13 @@ func (v *AuthenticationReader) nextChunk(mask uint16) error {
return errInsufficientBuffer
}
if size > readerBufferSize-2 {
return errors.New("size too large: ", size).Path("Common", "Crypto", "AuthenticationReader")
return newError("size too large: ", size)
}
if size == v.auth.Overhead() {
return io.EOF
}
if size < v.auth.Overhead() {
return errors.New("invalid packet size: ", size).Path("Common", "Crypto", "AuthenticationReader")
return newError("invalid packet size: ", size)
}
cipherChunk := v.buffer.BytesRange(2, size+2)
plainChunk, err := v.auth.Open(cipherChunk[:0], cipherChunk)

View File

@ -1,2 +1,4 @@
// Package crypto provides common crypto libraries for V2Ray.
package crypto
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg crypto -path Crypto

View File

@ -0,0 +1,5 @@
package crypto
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error { return errors.New(values...).Path("Crypto") }

View File

@ -1,4 +1,3 @@
// GENERATED CODE. DO NOT MODIFY!
package internal
import "encoding/binary"

View File

@ -0,0 +1,5 @@
package common
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error { return errors.New(values...).Path("Common") }

View File

@ -4,7 +4,6 @@ import (
"net"
"v2ray.com/core/app/log"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/predicate"
)
@ -95,7 +94,7 @@ func IPAddress(ip []byte) Address {
}
return addr
default:
log.Trace(errors.New("Net: Invalid IP format: ", ip).AtError())
log.Trace(newError("Net: Invalid IP format: ", ip).AtError())
return nil
}
}

View File

@ -0,0 +1,5 @@
package net
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error { return errors.New(values...).Path("Net") }

View File

@ -1,2 +1,4 @@
// Package net contains common network utilities.
package net
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg net -path Net

View File

@ -3,7 +3,6 @@ package net
import (
"strconv"
"v2ray.com/core/common/errors"
"v2ray.com/core/common/serial"
)
@ -20,7 +19,7 @@ func PortFromBytes(port []byte) Port {
// @error when the integer is not positive or larger then 65535
func PortFromInt(val uint32) (Port, error) {
if val > 65535 {
return Port(0), errors.New("Net: Invalid port range: ", val)
return Port(0), newError("Net: Invalid port range: ", val)
}
return Port(val), nil
}
@ -30,7 +29,7 @@ func PortFromInt(val uint32) (Port, error) {
func PortFromString(s string) (Port, error) {
val, err := strconv.ParseUint(s, 10, 32)
if err != nil {
return Port(0), errors.New("Net: Invalid port range: ", s)
return Port(0), newError("Net: Invalid port range: ", s)
}
return PortFromInt(uint32(val))
}

View File

@ -0,0 +1,5 @@
package protocol
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error { return errors.New(values...).Path("Protocol") }

View File

@ -0,0 +1,3 @@
package protocol
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg protocol -path Protocol

View File

@ -1,15 +1,11 @@
package protocol
import (
"time"
"v2ray.com/core/common/errors"
)
import "time"
var (
ErrAccountMissing = errors.New("Account is not specified.")
ErrNonMessageType = errors.New("Not a protobuf message.")
ErrUnknownAccountType = errors.New("Unknown account type.")
ErrAccountMissing = newError("Account is not specified.")
ErrNonMessageType = newError("Not a protobuf message.")
ErrUnknownAccountType = newError("Unknown account type.")
)
func (v *User) GetTypedAccount() (Account, error) {
@ -27,7 +23,7 @@ func (v *User) GetTypedAccount() (Account, error) {
if account, ok := rawAccount.(Account); ok {
return account, nil
}
return nil, errors.New("Unknown account type: ", v.Account.Type)
return nil, newError("Unknown account type: ", v.Account.Type)
}
func (v *User) GetSettings() UserSettings {

View File

@ -0,0 +1,5 @@
package retry
import "v2ray.com/core/common/errors"
func newError(values ...interface{}) *errors.Error { return errors.New(values...).Path("Retry") }

View File

@ -1,13 +1,13 @@
package retry
//go:generate go run $GOPATH/src/v2ray.com/core/tools/generrorgen/main.go -pkg retry -path Retry
import (
"time"
"v2ray.com/core/common/errors"
)
var (
ErrRetryFailed = errors.New("Retry: All retry attempts failed.")
ErrRetryFailed = newError("Retry: All retry attempts failed.")
)
// Strategy is a way to retry on a specific function.
@ -38,7 +38,7 @@ func (r *retryer) On(method func() error) error {
<-time.After(time.Duration(delay) * time.Millisecond)
attempt++
}
return errors.New(accumulatedError).Base(ErrRetryFailed)
return newError(accumulatedError).Base(ErrRetryFailed)
}
// Timed returns a retry strategy with fixed interval.

View File

@ -2,7 +2,6 @@ package common
import (
"context"
"errors"
"reflect"
)