generate exceptions in implementation

This commit is contained in:
Wolfgang Hottgenroth 2021-12-02 11:59:10 +01:00
parent fe9c431999
commit c9e54aebc8
Signed by: wn
GPG Key ID: E49AF3B9EF6DD469
7 changed files with 68 additions and 9 deletions

1
.gitignore vendored
View File

@ -6,4 +6,5 @@ OpenAPIDocCtrl.cs
tmp/ tmp/
*~ *~
.*~ .*~
ENV.database

View File

@ -37,6 +37,8 @@ namespace de.hottis.genericdatabaseapiservice.Services {
Console.WriteLine("ConnInfo: {0}", databaseConnInfo); Console.WriteLine("ConnInfo: {0}", databaseConnInfo);
Console.WriteLine("Statement: {0}", selectStatement); Console.WriteLine("Statement: {0}", selectStatement);
throw new Exception("AetschiBaetsch");
using (var conn = new MySqlConnection(databaseConnInfo)) { using (var conn = new MySqlConnection(databaseConnInfo)) {
await conn.OpenAsync(); await conn.OpenAsync();

View File

@ -13,6 +13,10 @@ parser.add_argument('--apiDefinitionFile', '-a',
help='API definition file. Default: openapi.yaml in the current folder.', help='API definition file. Default: openapi.yaml in the current folder.',
required=False, required=False,
default='./openapi.yaml') default='./openapi.yaml')
parser.add_argument('--errorDefinitionFile', '-e',
help='Error definition file. Default: serviceErrorCodes.yaml in the current folder.',
required=False,
default='./serviceErrorCodes.yaml')
parser.add_argument('--template', '-t', parser.add_argument('--template', '-t',
help="""Template file, templates files must be named as the final output file help="""Template file, templates files must be named as the final output file
with an additional .tmpl extension. Default: all template files recursively from the current folder.""", with an additional .tmpl extension. Default: all template files recursively from the current folder.""",
@ -23,6 +27,9 @@ args = parser.parse_args()
with open(args.apiDefinitionFile) as apiDefinitionFile: with open(args.apiDefinitionFile) as apiDefinitionFile:
apiDefinition = yaml.load(apiDefinitionFile, Loader=SafeLoader) apiDefinition = yaml.load(apiDefinitionFile, Loader=SafeLoader)
with open(args.errorDefinitionFile) as errorDefinitionFile:
errorDefinition = yaml.load(errorDefinitionFile, Loader=SafeLoader)
apiDefinition["GENERATED_SQL_COMMENT"] = """ apiDefinition["GENERATED_SQL_COMMENT"] = """
@ -142,9 +149,10 @@ for (typeName, typeDefinition) in apiDefinition['components']['schemas'].items()
apiDefinition['types'] = types apiDefinition['types'] = types
print(json.dumps(apiDefinition, indent=4)) print(json.dumps(apiDefinition, indent=4))
print(json.dumps(errorDefinition, indent=4))
for f in glob.glob(args.template, recursive=True): for f in glob.glob(args.template, recursive=True):
print(f"process {f}") print(f"process {f}")
tmpl = Template(file=f, searchList=[apiDefinition]) tmpl = Template(file=f, searchList=[apiDefinition, errorDefinition])
with open(f[:-5], 'w') as outFile: with open(f[:-5], 'w') as outFile:
outFile.write(str(tmpl)) outFile.write(str(tmpl))

View File

@ -62,6 +62,11 @@ fi
# PACKAGE_NAME will be loaded here # PACKAGE_NAME will be loaded here
. ENV . ENV
if [ -f ENV.database ]; then
echo "database environment loaded"
. ENV.database
fi
if [ "$STAGE1" = "1" ]; then if [ "$STAGE1" = "1" ]; then
echo "generate endpoint code from openapi.yaml" echo "generate endpoint code from openapi.yaml"
python3.10 generate.py python3.10 generate.py

View File

@ -97,6 +97,12 @@ paths:
application/json: application/json:
schema: schema:
$ref: "#/components/schemas/errorResultObject" $ref: "#/components/schemas/errorResultObject"
500:
description: Internal Server Error
content:
application/json:
schema:
$ref: "#/components/schemas/errorResultObject"
/pdb/v2/baseData/{articleNumber}: /pdb/v2/baseData/{articleNumber}:
get: get:
tags: [ "Regular" ] tags: [ "Regular" ]
@ -145,6 +151,9 @@ components:
errorInfoURL: errorInfoURL:
description: URL to some more information on the error description: URL to some more information on the error
type: string type: string
offensiveData:
description: Input data which causes this error
type: string
test1: test1:
description: A test1 item description: A test1 item
type: object type: object

View File

@ -117,15 +117,31 @@ null#slurp
[0]#slurp [0]#slurp
#end if #end if
); );
} catch (NotDataFoundException) { \#pragma warning disable CS0168
#for $errDef in $Exceptions
} catch ($errDef['Exception'] ex) {
var err = new ErrorResultObject(); var err = new ErrorResultObject();
err.errorCode = 400; err.ErrorCode = $errDef['ErrorCode'];
err.serviceErrorCode = 517; err.ServiceErrorCode = $errDef['ServiceErrorCode'];
err.errorMessage("item not found"); err.ErrorMessage = #slurp
err.errorInfoURL("https://google.com"); #if $errDef['ErrorMessage'] == 'INSERT_EXCEPTION_MESSAGE'
return BadRequest(err); ex.ToString();
} #else
"$errDef['ErrorMessage']";
#end if
err.ErrorInfoURL = "$errDef['ErrorInfoURL']";
err.OffensiveData = #slurp
#if $operation['bodyInputType']
Newtonsoft.Json.JsonConvert.SerializeObject($operation['bodyInputType']['apiName'], Newtonsoft.Json.Formatting.Indented);
#elif $operation['paramInputTypes']
Newtonsoft.Json.JsonConvert.SerializeObject(paramInput, Newtonsoft.Json.Formatting.Indented);
#else
null;
#end if
return StatusCode($errDef['ErrorCode'], err);
#end for
}
\#pragma warning restore CS0168
} }
#elif $operation['method'] == 'post' #elif $operation['method'] == 'post'

18
serviceErrorCodes.yaml Normal file
View File

@ -0,0 +1,18 @@
# ONLY USE THE ERRORCODES 400 and 500 HERE
Exceptions:
- Exception: NotDataFoundException
ErrorCode: 400
ServiceErrorCode: 10001
ErrorMessage: item not found
ErrorInfoURL: https://google.com
- Exception: TooMuchDataFoundException
ErrorCode: 400
ServiceErrorCode: 10002
ErrorMessage: too many items found
ErrorInfoURL: https://google.com
# Make sure "Exception: Exception" is the last entry in the list
- Exception: Exception
ErrorCode: 500
ServiceErrorCode: 10000
ErrorMessage: INSERT_EXCEPTION_MESSAGE
ErrorInfoURL: https://google.com