Adding fancy exceptions messages

OneViewException and its subclasses are meant to have a default message that can
be overwritten by passing a custom message in the instantiation method. This
patch ensure it happens without aid of the builtin class Exception and
overwrite __str__ to include information about the class of the exception being
thrown to ease debug.

To obtain just the exception message, users can still access the exc.message
variable.

Change-Id: I278e38dadf9b612009156ecfce62a0d31e9caa94
This commit is contained in:
Thiago Paiva 2016-02-04 11:29:06 -03:00
parent d34e644a8f
commit 6935bd2f06
2 changed files with 45 additions and 0 deletions

View File

@ -19,6 +19,13 @@
class OneViewException(Exception):
message = ("An error occurred in the OneView client.")
def __init__(self, msg=None):
if msg:
self.message = msg
def __str__(self):
return "<%s> %s" % (self.__class__.__name__, self.message)
class OneViewConnectionError(OneViewException):
message = ("Can't connect to OneView")

View File

@ -0,0 +1,38 @@
# -*- encoding: utf-8 -*-
#
# (c) Copyright 2015 Hewlett Packard Enterprise Development LP
# Copyright 2015 Universidade Federal de Campina Grande
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import unittest
from oneview_client import exceptions
class Test(unittest.TestCase):
def test_create_OneViewException_default_message(self):
exc = exceptions.OneViewException()
self.assertEqual(
str(exc),
"<%s> %s" % (exc.__class__.__name__, exc.message)
)
def test_create_OneViewException_message(self):
msg = "This is a custom message"
exc = exceptions.OneViewException(msg)
self.assertEqual(
str(exc),
"<%s> %s" % (exc.__class__.__name__, msg)
)