We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
duplicated errors when validators raise ValidationError
# Bug

As a work around for #619 I tried the following

```py
from pydantic import VERSION, BaseModel, Union, validator
from typing_extensions import Literal
print('pydantic version:', VERSION)

class Foo(BaseModel):
    model_type: Literal['foo']
    f: int

class Bar(BaseModel):
    model_type: Literal['bar']
    b: int

class MyModel(BaseModel):
    foobar: Union[Foo, Bar]

    @validator('foobar', pre=True)
    def check_action(cls, v):
        if isinstance(v, dict):
            model_type = v.get('model_type')
            if model_type == 'foo':
                return Foo(**v)
            if model_type == 'var':
                return Bar(**v)
        return v

MyModel(foobar={'model_type': 'foo', 'f': 'x'})
```
Output:
```
pydantic version: 0.32.1
Traceback (most recent call last):
  File "test.py", line 31, in <module>
    MyModel(foobar={'model_type': 'foo', 'f': 'x'})
  File "pydantic/main.py", line 275, in pydantic.main.BaseModel.__init__
  File "pydantic/main.py", line 785, in pydantic.main.validate_model
pydantic.error_wrappers.ValidationError: 2 validation errors for MyModel
foobar -> f
  value is not a valid integer (type=type_error.integer)
foobar -> f
  value is not a valid integer (type=type_error.integer)
```

When validators raise `ValidationError` the errors are duplicated.

Won't be that common, but should be fixed.


Repeated error when validator raises an exception
# Bug

Please complete:
* OS: **Ubuntu**
* Python version `import sys; print(sys.version)`: **3.7.4**
* Pydantic version `import pydantic; print(pydantic.VERSION)`: **v0.32.1**

```py
from typing import Optional

from pydantic import BaseModel, validator

class Foobar(BaseModel):
    foo: Optional[str] = None

    @validator('foo', always=True)
    def check_foo(cls, v):
        if not v:
            raise ValueError('custom error, foo is required')
        return v

print(Foobar(foo='x'))
print(Foobar())
```

Outputs:
```
pydantic.error_wrappers.ValidationError: 2 validation errors for Foobar
foo
  none is not an allowed value (type=type_error.none.not_allowed)
foo
  custom error, foo is required (type=value_error)
```

If i add `pre=True`, the error is even weirder:
```
pydantic.error_wrappers.ValidationError: 2 validation errors for Foobar
foo
  custom error, foo is required (type=value_error)
foo
  custom error, foo is required (type=value_error)
```

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `pydantic/error_wrappers.py`
Content:
```
1 import json
2 from functools import lru_cache
3 from typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Sequence, Tuple, Type, Union
4 
5 if TYPE_CHECKING:  # pragma: no cover
6     from pydantic import BaseConfig  # noqa: F401
7 
8 __all__ = ('ErrorWrapper', 'ValidationError')
9 
10 
11 class ErrorWrapper:
12     __slots__ = 'exc', 'type_', 'loc', 'msg_template'
13 
14     def __init__(
15         self, exc: Exception, *, loc: Union[Tuple[str, ...], str], config: Optional[Type['BaseConfig']] = None
16     ) -> None:
17         self.exc = exc
18         self.type_ = get_exc_type(type(exc))
19         self.loc: Tuple[str, ...] = loc if isinstance(loc, tuple) else (loc,)  # type: ignore
20         self.msg_template = config.error_msg_templates.get(self.type_) if config else None
21 
22     @property
23     def ctx(self) -> Dict[str, Any]:
24         return getattr(self.exc, 'ctx', None)
25 
26     @property
27     def msg(self) -> str:
28         default_msg_template = getattr(self.exc, 'msg_template', None)
29         msg_template = self.msg_template or default_msg_template
30         if msg_template:
31             return msg_template.format(**self.ctx or {})
32 
33         return str(self.exc)
34 
35     def dict(self, *, loc_prefix: Optional[Tuple[str, ...]] = None) -> Dict[str, Any]:
36         loc = self.loc if loc_prefix is None else loc_prefix + self.loc
37 
38         d: Dict[str, Any] = {'loc': loc, 'msg': self.msg, 'type': self.type_}
39 
40         if self.ctx is not None:
41             d['ctx'] = self.ctx
42 
43         return d
44 
45 
46 # ErrorList is something like Union[List[Union[List[ErrorWrapper], ErrorWrapper]], ErrorWrapper]
47 # but recursive, therefore just use:
48 ErrorList = Union[Sequence[Any], ErrorWrapper]
49 
50 
51 class ValidationError(ValueError):
52     __slots__ = ('raw_errors', 'model')
53 
54     def __init__(self, errors: Sequence[ErrorList], model: Type[Any]) -> None:
55         self.raw_errors = errors
56         self.model = model
57 
58     @lru_cache()
59     def errors(self) -> List[Dict[str, Any]]:
60         return list(flatten_errors(self.raw_errors))
61 
62     def json(self, *, indent: Union[None, int, str] = 2) -> str:
63         return json.dumps(self.errors(), indent=indent)
64 
65     def __str__(self) -> str:
66         errors = self.errors()
67         no_errors = len(errors)
68         return (
69             f'{no_errors} validation error{"" if no_errors == 1 else "s"} for {self.model.__name__}\n'
70             f'{display_errors(errors)}'
71         )
72 
73 
74 def display_errors(errors: List[Dict[str, Any]]) -> str:
75     return '\n'.join(f'{_display_error_loc(e)}\n  {e["msg"]} ({_display_error_type_and_ctx(e)})' for e in errors)
76 
77 
78 def _display_error_loc(error: Dict[str, Any]) -> str:
79     return ' -> '.join(str(l) for l in error['loc'])
80 
81 
82 def _display_error_type_and_ctx(error: Dict[str, Any]) -> str:
83     t = 'type=' + error['type']
84     ctx = error.get('ctx')
85     if ctx:
86         return t + ''.join(f'; {k}={v}' for k, v in ctx.items())
87     else:
88         return t
89 
90 
91 def flatten_errors(
92     errors: Sequence[Any], *, loc: Optional[Tuple[str, ...]] = None
93 ) -> Generator[Dict[str, Any], None, None]:
94     for error in errors:
95         if isinstance(error, ErrorWrapper):
96             if isinstance(error.exc, ValidationError):
97                 if loc is not None:
98                     error_loc = loc + error.loc
99                 else:
100                     error_loc = error.loc
101                 yield from flatten_errors(error.exc.raw_errors, loc=error_loc)
102             else:
103                 yield error.dict(loc_prefix=loc)
104         elif isinstance(error, list):
105             yield from flatten_errors(error)
106         else:
107             raise RuntimeError(f'Unknown error object: {error}')
108 
109 
110 @lru_cache()
111 def get_exc_type(cls: Type[Exception]) -> str:
112 
113     base_name = 'type_error' if issubclass(cls, TypeError) else 'value_error'
114     if cls in (TypeError, ValueError):
115         # just TypeError or ValueError, no extra code
116         return base_name
117 
118     # if it's not a TypeError or ValueError, we just take the lowercase of the exception name
119     # no chaining or snake case logic, use "code" for more complex error types.
120     code = getattr(cls, 'code', None) or cls.__name__.replace('Error', '').lower()
121     return base_name + '.' + code
122
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/pydantic/error_wrappers.py b/pydantic/error_wrappers.py
--- a/pydantic/error_wrappers.py
+++ b/pydantic/error_wrappers.py
@@ -42,6 +42,9 @@
 
         return d
 
+    def __repr__(self) -> str:
+        return f'<ErrorWrapper {self.dict()}>'
+
 
 # ErrorList is something like Union[List[Union[List[ErrorWrapper], ErrorWrapper]], ErrorWrapper]
 # but recursive, therefore just use:

{"golden_diff": "diff --git a/pydantic/error_wrappers.py b/pydantic/error_wrappers.py\n--- a/pydantic/error_wrappers.py\n+++ b/pydantic/error_wrappers.py\n@@ -42,6 +42,9 @@\n \n         return d\n \n+    def __repr__(self) -> str:\n+        return f'<ErrorWrapper {self.dict()}>'\n+\n \n # ErrorList is something like Union[List[Union[List[ErrorWrapper], ErrorWrapper]], ErrorWrapper]\n # but recursive, therefore just use:\n", "issue": "duplicated errors when validators raise ValidationError\n# Bug\r\n\r\nAs a work around for #619 I tried the following\r\n\r\n```py\r\nfrom pydantic import VERSION, BaseModel, Union, validator\r\nfrom typing_extensions import Literal\r\nprint('pydantic version:', VERSION)\r\n\r\nclass Foo(BaseModel):\r\n    model_type: Literal['foo']\r\n    f: int\r\n\r\nclass Bar(BaseModel):\r\n    model_type: Literal['bar']\r\n    b: int\r\n\r\nclass MyModel(BaseModel):\r\n    foobar: Union[Foo, Bar]\r\n\r\n    @validator('foobar', pre=True)\r\n    def check_action(cls, v):\r\n        if isinstance(v, dict):\r\n            model_type = v.get('model_type')\r\n            if model_type == 'foo':\r\n                return Foo(**v)\r\n            if model_type == 'var':\r\n                return Bar(**v)\r\n        return v\r\n\r\nMyModel(foobar={'model_type': 'foo', 'f': 'x'})\r\n```\r\nOutput:\r\n```\r\npydantic version: 0.32.1\r\nTraceback (most recent call last):\r\n  File \"test.py\", line 31, in <module>\r\n    MyModel(foobar={'model_type': 'foo', 'f': 'x'})\r\n  File \"pydantic/main.py\", line 275, in pydantic.main.BaseModel.__init__\r\n  File \"pydantic/main.py\", line 785, in pydantic.main.validate_model\r\npydantic.error_wrappers.ValidationError: 2 validation errors for MyModel\r\nfoobar -> f\r\n  value is not a valid integer (type=type_error.integer)\r\nfoobar -> f\r\n  value is not a valid integer (type=type_error.integer)\r\n```\r\n\r\nWhen validators raise `ValidationError` the errors are duplicated.\r\n\r\nWon't be that common, but should be fixed.\r\n\r\n\nRepeated error when validator raises an exception\n# Bug\r\n\r\nPlease complete:\r\n* OS: **Ubuntu**\r\n* Python version `import sys; print(sys.version)`: **3.7.4**\r\n* Pydantic version `import pydantic; print(pydantic.VERSION)`: **v0.32.1**\r\n\r\n```py\r\nfrom typing import Optional\r\n\r\nfrom pydantic import BaseModel, validator\r\n\r\nclass Foobar(BaseModel):\r\n    foo: Optional[str] = None\r\n\r\n    @validator('foo', always=True)\r\n    def check_foo(cls, v):\r\n        if not v:\r\n            raise ValueError('custom error, foo is required')\r\n        return v\r\n\r\nprint(Foobar(foo='x'))\r\nprint(Foobar())\r\n```\r\n\r\nOutputs:\r\n```\r\npydantic.error_wrappers.ValidationError: 2 validation errors for Foobar\r\nfoo\r\n  none is not an allowed value (type=type_error.none.not_allowed)\r\nfoo\r\n  custom error, foo is required (type=value_error)\r\n```\r\n\r\nIf i add `pre=True`, the error is even weirder:\r\n```\r\npydantic.error_wrappers.ValidationError: 2 validation errors for Foobar\r\nfoo\r\n  custom error, foo is required (type=value_error)\r\nfoo\r\n  custom error, foo is required (type=value_error)\r\n```\n", "before_files": [{"content": "import json\nfrom functools import lru_cache\nfrom typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Sequence, Tuple, Type, Union\n\nif TYPE_CHECKING:  # pragma: no cover\n    from pydantic import BaseConfig  # noqa: F401\n\n__all__ = ('ErrorWrapper', 'ValidationError')\n\n\nclass ErrorWrapper:\n    __slots__ = 'exc', 'type_', 'loc', 'msg_template'\n\n    def __init__(\n        self, exc: Exception, *, loc: Union[Tuple[str, ...], str], config: Optional[Type['BaseConfig']] = None\n    ) -> None:\n        self.exc = exc\n        self.type_ = get_exc_type(type(exc))\n        self.loc: Tuple[str, ...] = loc if isinstance(loc, tuple) else (loc,)  # type: ignore\n        self.msg_template = config.error_msg_templates.get(self.type_) if config else None\n\n    @property\n    def ctx(self) -> Dict[str, Any]:\n        return getattr(self.exc, 'ctx', None)\n\n    @property\n    def msg(self) -> str:\n        default_msg_template = getattr(self.exc, 'msg_template', None)\n        msg_template = self.msg_template or default_msg_template\n        if msg_template:\n            return msg_template.format(**self.ctx or {})\n\n        return str(self.exc)\n\n    def dict(self, *, loc_prefix: Optional[Tuple[str, ...]] = None) -> Dict[str, Any]:\n        loc = self.loc if loc_prefix is None else loc_prefix + self.loc\n\n        d: Dict[str, Any] = {'loc': loc, 'msg': self.msg, 'type': self.type_}\n\n        if self.ctx is not None:\n            d['ctx'] = self.ctx\n\n        return d\n\n\n# ErrorList is something like Union[List[Union[List[ErrorWrapper], ErrorWrapper]], ErrorWrapper]\n# but recursive, therefore just use:\nErrorList = Union[Sequence[Any], ErrorWrapper]\n\n\nclass ValidationError(ValueError):\n    __slots__ = ('raw_errors', 'model')\n\n    def __init__(self, errors: Sequence[ErrorList], model: Type[Any]) -> None:\n        self.raw_errors = errors\n        self.model = model\n\n    @lru_cache()\n    def errors(self) -> List[Dict[str, Any]]:\n        return list(flatten_errors(self.raw_errors))\n\n    def json(self, *, indent: Union[None, int, str] = 2) -> str:\n        return json.dumps(self.errors(), indent=indent)\n\n    def __str__(self) -> str:\n        errors = self.errors()\n        no_errors = len(errors)\n        return (\n            f'{no_errors} validation error{\"\" if no_errors == 1 else \"s\"} for {self.model.__name__}\\n'\n            f'{display_errors(errors)}'\n        )\n\n\ndef display_errors(errors: List[Dict[str, Any]]) -> str:\n    return '\\n'.join(f'{_display_error_loc(e)}\\n  {e[\"msg\"]} ({_display_error_type_and_ctx(e)})' for e in errors)\n\n\ndef _display_error_loc(error: Dict[str, Any]) -> str:\n    return ' -> '.join(str(l) for l in error['loc'])\n\n\ndef _display_error_type_and_ctx(error: Dict[str, Any]) -> str:\n    t = 'type=' + error['type']\n    ctx = error.get('ctx')\n    if ctx:\n        return t + ''.join(f'; {k}={v}' for k, v in ctx.items())\n    else:\n        return t\n\n\ndef flatten_errors(\n    errors: Sequence[Any], *, loc: Optional[Tuple[str, ...]] = None\n) -> Generator[Dict[str, Any], None, None]:\n    for error in errors:\n        if isinstance(error, ErrorWrapper):\n            if isinstance(error.exc, ValidationError):\n                if loc is not None:\n                    error_loc = loc + error.loc\n                else:\n                    error_loc = error.loc\n                yield from flatten_errors(error.exc.raw_errors, loc=error_loc)\n            else:\n                yield error.dict(loc_prefix=loc)\n        elif isinstance(error, list):\n            yield from flatten_errors(error)\n        else:\n            raise RuntimeError(f'Unknown error object: {error}')\n\n\n@lru_cache()\ndef get_exc_type(cls: Type[Exception]) -> str:\n\n    base_name = 'type_error' if issubclass(cls, TypeError) else 'value_error'\n    if cls in (TypeError, ValueError):\n        # just TypeError or ValueError, no extra code\n        return base_name\n\n    # if it's not a TypeError or ValueError, we just take the lowercase of the exception name\n    # no chaining or snake case logic, use \"code\" for more complex error types.\n    code = getattr(cls, 'code', None) or cls.__name__.replace('Error', '').lower()\n    return base_name + '.' + code\n", "path": "pydantic/error_wrappers.py"}], "after_files": [{"content": "import json\nfrom functools import lru_cache\nfrom typing import TYPE_CHECKING, Any, Dict, Generator, List, Optional, Sequence, Tuple, Type, Union\n\nif TYPE_CHECKING:  # pragma: no cover\n    from pydantic import BaseConfig  # noqa: F401\n\n__all__ = ('ErrorWrapper', 'ValidationError')\n\n\nclass ErrorWrapper:\n    __slots__ = 'exc', 'type_', 'loc', 'msg_template'\n\n    def __init__(\n        self, exc: Exception, *, loc: Union[Tuple[str, ...], str], config: Optional[Type['BaseConfig']] = None\n    ) -> None:\n        self.exc = exc\n        self.type_ = get_exc_type(type(exc))\n        self.loc: Tuple[str, ...] = loc if isinstance(loc, tuple) else (loc,)  # type: ignore\n        self.msg_template = config.error_msg_templates.get(self.type_) if config else None\n\n    @property\n    def ctx(self) -> Dict[str, Any]:\n        return getattr(self.exc, 'ctx', None)\n\n    @property\n    def msg(self) -> str:\n        default_msg_template = getattr(self.exc, 'msg_template', None)\n        msg_template = self.msg_template or default_msg_template\n        if msg_template:\n            return msg_template.format(**self.ctx or {})\n\n        return str(self.exc)\n\n    def dict(self, *, loc_prefix: Optional[Tuple[str, ...]] = None) -> Dict[str, Any]:\n        loc = self.loc if loc_prefix is None else loc_prefix + self.loc\n\n        d: Dict[str, Any] = {'loc': loc, 'msg': self.msg, 'type': self.type_}\n\n        if self.ctx is not None:\n            d['ctx'] = self.ctx\n\n        return d\n\n    def __repr__(self) -> str:\n        return f'<ErrorWrapper {self.dict()}>'\n\n\n# ErrorList is something like Union[List[Union[List[ErrorWrapper], ErrorWrapper]], ErrorWrapper]\n# but recursive, therefore just use:\nErrorList = Union[Sequence[Any], ErrorWrapper]\n\n\nclass ValidationError(ValueError):\n    __slots__ = ('raw_errors', 'model')\n\n    def __init__(self, errors: Sequence[ErrorList], model: Type[Any]) -> None:\n        self.raw_errors = errors\n        self.model = model\n\n    @lru_cache()\n    def errors(self) -> List[Dict[str, Any]]:\n        return list(flatten_errors(self.raw_errors))\n\n    def json(self, *, indent: Union[None, int, str] = 2) -> str:\n        return json.dumps(self.errors(), indent=indent)\n\n    def __str__(self) -> str:\n        errors = self.errors()\n        no_errors = len(errors)\n        return (\n            f'{no_errors} validation error{\"\" if no_errors == 1 else \"s\"} for {self.model.__name__}\\n'\n            f'{display_errors(errors)}'\n        )\n\n\ndef display_errors(errors: List[Dict[str, Any]]) -> str:\n    return '\\n'.join(f'{_display_error_loc(e)}\\n  {e[\"msg\"]} ({_display_error_type_and_ctx(e)})' for e in errors)\n\n\ndef _display_error_loc(error: Dict[str, Any]) -> str:\n    return ' -> '.join(str(l) for l in error['loc'])\n\n\ndef _display_error_type_and_ctx(error: Dict[str, Any]) -> str:\n    t = 'type=' + error['type']\n    ctx = error.get('ctx')\n    if ctx:\n        return t + ''.join(f'; {k}={v}' for k, v in ctx.items())\n    else:\n        return t\n\n\ndef flatten_errors(\n    errors: Sequence[Any], *, loc: Optional[Tuple[str, ...]] = None\n) -> Generator[Dict[str, Any], None, None]:\n    for error in errors:\n        if isinstance(error, ErrorWrapper):\n            if isinstance(error.exc, ValidationError):\n                if loc is not None:\n                    error_loc = loc + error.loc\n                else:\n                    error_loc = error.loc\n                yield from flatten_errors(error.exc.raw_errors, loc=error_loc)\n            else:\n                yield error.dict(loc_prefix=loc)\n        elif isinstance(error, list):\n            yield from flatten_errors(error)\n        else:\n            raise RuntimeError(f'Unknown error object: {error}')\n\n\n@lru_cache()\ndef get_exc_type(cls: Type[Exception]) -> str:\n\n    base_name = 'type_error' if issubclass(cls, TypeError) else 'value_error'\n    if cls in (TypeError, ValueError):\n        # just TypeError or ValueError, no extra code\n        return base_name\n\n    # if it's not a TypeError or ValueError, we just take the lowercase of the exception name\n    # no chaining or snake case logic, use \"code\" for more complex error types.\n    code = getattr(cls, 'code', None) or cls.__name__.replace('Error', '').lower()\n    return base_name + '.' + code\n", "path": "pydantic/error_wrappers.py"}]}