Prefered way is to use Operator.report() method. You only need to pass a certain type of report 'INFO', 'ERROR', 'WARNING'
etc. and the corresponding message as string. In case of an error report a popup appears as well as the message is shown in the info bar, automatically.

import bpy
import random
class SimpleOperator(bpy.types.Operator):
"""Tooltip"""
bl_idname = "object.simple_operator"
bl_label = "Simple Object Operator"
@classmethod
def poll(cls, context):
return context.active_object is not None
def execute(self, context):
if bool(random.getrandbits(1)):
self.report({'ERROR'}, 'Error message')
else:
self.report({'INFO'}, 'Info message')
return {'FINISHED'}
def register():
bpy.utils.register_class(SimpleOperator)
def unregister():
bpy.utils.unregister_class(SimpleOperator)
if __name__ == "__main__":
register()
Example based on Python > Templates > Operator Simple.