this quick guide will show you a few easy steps to add any number of custom error codes. These can be used with the Login Handler to provide special login errors to the client. Make sure to run SFS2X version 2.0.1 or higher and let's get started!
» Server Side
Let's say we want to create our custom login handler and we will need two new custom errors:
- Invalid age: users below a certain age will not be allowed.
Human verification test: to avoid bots, we'll add a question at login time to verify if the client is human or not.
Code: Select all
import com.smartfoxserver.v2.exceptions.IErrorCode;
public enum MyCustomErrors implements IErrorCode
{
AGE_IS_NOT_VALID(200),
HUMAN_VERIFICATION_FAIL(201);
private MyCustomErrors(int id)
{
this.id = (short) id;
}
private short id;
@Override
public short getId()
{
return id;
}
}
Next we create our basic Login Handler class:
Code: Select all
import com.smartfoxserver.v2.core.ISFSEvent;
import com.smartfoxserver.v2.core.SFSEventParam;
import com.smartfoxserver.v2.exceptions.SFSErrorData;
import com.smartfoxserver.v2.exceptions.SFSException;
import com.smartfoxserver.v2.exceptions.SFSLoginException;
import com.smartfoxserver.v2.extensions.BaseServerEventHandler;
public class CustomLoginHandler extends BaseServerEventHandler
{
@Override
public void handleServerEvent(ISFSEvent event) throws SFSException
{
String uName = (String) event.getParameter(SFSEventParam.LOGIN_NAME);
SFSErrorData ed = new SFSErrorData(MyCustomErrors.HUMAN_VERIFICATION_FAIL);
ed.addParameter(uName);
throw new SFSLoginException("Wrong answer, are you human?", ed);
}
}Please note that we are sending one extra parmeter, the name of the user attempting the login.
Finally, here's the code of the main extension file to complete the server side part:
Code: Select all
import com.smartfoxserver.v2.core.SFSEventType;
import com.smartfoxserver.v2.extensions.SFSExtension;
public class CustomErrorExtension extends SFSExtension
{
@Override
public void init()
{
addEventHandler(SFSEventType.USER_LOGIN, CustomLoginHandler.class);
}
@Override
public void destroy()
{
super.destroy();
}
}On the client we just need to define the new code and provide a String in any language that will be used to compose the message.
This is how it is done in Actionscript 3. The same will also work in C#, Java, Objective-C etc...
Code: Select all
SFSErrorCodes.setErrorMessage(201, "Sorry {0}, you don't seem to be a human user. Nice try!")Voilà! As simple as that!
Cheers
Lapo