File System: Error Handling

Table of Contents

Overview

This page describes error handling for the file system.

Result Handling

FS functions return many different types of Result values. These are handled by the following mechanism rather than one value at a time. The following example shows how to handle all errors belonging to the ResultNotFound category.
if(result <= nn::fs::ResultNotFound())
{
    // This can catch nn::fs::ResultMediaNotFound as well.
}
The Result objects returned by fs functions are forbidden from using the arithmetic operators == or !=. Using these causes a build error. Also note that the following two examples are equivalent.
if(nn::fs::ResultNotFound::Includes(result))
{
    ...
}
if(nn::fs::ResultNotFound() >= result)
{
    ...
}

Do not directly handle any Result values that are not mentioned in the Function Reference Manual.

Errors That Must Not Be Allowed to Occur in Retail Products

The following Result values indicate errors that are caused by application bugs and other such problems. You must fix your program so that these do not occur in retail products. The Result values listed above may be caused by user operations or it may be impossible to get rid of them entirely during development. You must handle errors that can be caused by the user. Some functions may also specify errors that must not occur in retail products, even though the corresponding Result values are not among those listed above. For more information, see the documentation for each of these functions in the Function Reference Manual.

Functions for File and Directory Operations

There are two types of functions used to perform file and directory operations: Try functions (which have the prefix Try added to the function name), and non-Try functions (which do not contain this prefix). Try functions return a Result as the return value, unless a fatal internal error occurs. Instead of returning Results, non-Try functions are implemented to display a fatal error screen whenever an internal error returns, regardless of whether the error is fatal. Control does not return from the function in this case.

Internal errors never occur for ROM archives because of their characteristics. For ROM archives, implementation omissions in error handling can be avoided by using the non-Try functions. (During development, make sure to eliminate situations in which an error could occur because of an attempt to open a nonexistent file.)

For archives other than ROM archives, you must always check for errors that can result from the user's operations. One typical example is removal of the Game Card by the user, which can lead to corrupted files. As a result, Try functions should always be used for error handling. Do not use non-Try functions because they can easily jump to fatal error screens as a result of user operations.

Handling Fatal Errors

You are allowed to use the following macro to jump to the fatal error screen when a file system API function returns an error that you believe to be fatal, or there is a system issue that your application cannot handle.

Note, however, that applications must handle all errors other than those given in the following examples. Do not call this function in locations other than given in examples in order to prevent unnecessary transition to the fatal error screen.
NN_ERR_THROW_FATAL_ALL(result);
See the Error Handling page for details about this macro.

Handling Mount Errors

The following simplified C++ code provides guidelines for handling mount errors.

ROM Archives

// An error will cause an internal jump to the fatal error screen.
// The application does not need to perform error handling.
// NOTE: When developing an application, confirm that you are passing enough working memory as an argument.
//       Also check your Omakefile and RSF file settings to determine whether a ROMFS is created at build time.
nn::fs::MountRom();

Save Data Archives

nn::Result result = nn::fs::MountSaveData();

if(result.IsFailure())
{
    if(result <= nn::fs::ResultNotFormatted())
    {
        // Formatting required.
        // CAUSE: Unformatted save data region.
        // NOTE: You must always format a save data region before mounting it for the first time.
        result = nn::fs::FormatSaveData();
    }
    else if(result <= nn::fs::ResultBadFormat())
    {
        // Formatting required.
        // CAUSE: Invalid file format.
        result = nn::fs::FormatSaveData();
    }
    else if(result <= nn::fs::ResultVerificationFailed())
    {
        // Formatting required.
        // CAUSE: Corrupted or tampered-with save data.
        // (Supplement) This may occur whether or not there is a duplication.
        result = nn::fs::FormatSaveData();
    }
    else if(result <= nn::fs::ResultOperationDenied())
    {
        // As of CTR-SDK 2.1, this error is handled by the system. Treat it as an unexpected error.
    }
    else
    {
        // Unexpected error if other than the above.
        NN_ERR_THROW_FATAL_ALL(result);
    }

    // Troubleshooting after formatting 
    if(result.IsFailure())
    {
        // Here, the act of formatting save data never fails.
        // NOTE: When developing your application, confirm that the maxFiles and maxDirectories arguments are not too big.
        //       Also confirm that the content of the RSF file is correct.
        // NOTE: Do not format the region while it is mounted, or access save data from another thread during formatting.
        NN_ERR_THROW_FATAL_ALL(result);
    }
    else
    {
        // Remount
        result = nn::fs::MountSaveData();
        if(result.IsFailure())
        {
            // The same as when making the first call.
            // NOTE: Do not format the region while it is mounted, or access save data from another thread during formatting.
        }
    }
}

Save Data Archives (Other Programs)

nn::Result result = nn::fs::MountSaveData(archiveName, uniqueId, variation);

if(result.IsFailure())
{
    if(result <= nn::fs::ResultNotFound())
    {
        // Stop access.
        // Reason: Target save data not found.
    }
    else if(result <= nn::fs::ResultNotFormatted() || result <= nn::fs::ResultBadFormat())
    {
        // Stop access.
        // Reason: Target save data not formatted correctly.
        // Comment: To use the save data it needs to be formatted by the program to which it belongs.
    }
    else if(result <= nn::fs::ResultVerificationFailed())
    {
        // Stop access.
        // Reason: Target save data is corrupt.
        // Comment: To use the save data it needs to be formatted by the program to which it belongs.
    }
    else if(result <= nn::fs::ResultOperationDenied())
    {
        // Stop access.
        // Reason: Cannot access the target media.
        // Comment: This might be resolved by removing and re-inserting the target media.
    }
    else
    {
        // Unexpected error if other than the above.
        // Do not call "NN_ERR_THROW_FATAL" macros.
    }
}

Expanded Save Data Archives

nn::Result result = nn::fs::MountExtSaveData();

if(result.IsFailure())
{
    if(result <= nn::fs::ResultNotFound())
    {
        if(result <= nn::fs::ResultMediaNotFound())
        {
            // An SD Card has not been inserted.
            // Note: This error is also returned if the SD Card is damaged or if some medium other than an SD Card is inserted.
            //        In such cases, an insertion event registered by RegisterSdmcInsertedEvent is signaled.
        }
        else
        {
            // The specified expanded save data does not exist and must be created.
            // NOTE: Confirm that the ID you specified is correct when developing your application.
            result = nn::fs::CreateExtSaveData();
        }
    }
    else if(result <= nn::fs::ResultNotFormatted())
    {
        // You must recreate the expanded save data.
        // CAUSE: Failed to create expanded save data.
        result = nn::fs::DeleteExtSaveData();
        if(result.IsSuccess())
        {
            result = nn::fs::CreateExtSaveData();
        }
    }
    else if(result <= nn::fs::ResultBadFormat())
    {
        // You must format the SD Card.
    }
    else if(result <= nn::fs::ResultVerificationFailed())
    {
        // You must recreate the expanded save data.
        // CAUSE: The save data has been corrupted or tampered with.
        result = nn::fs::DeleteExtSaveData();
        if(result.IsSuccess())
        {
            result = nn::fs::CreateExtSaveData();
        }
    }
    else if(result <= nn::fs::ResultOperationDenied())
    {
        if(result <= nn::fs::ResultWriteProtected())
        {
            // The SD Card is write-protected.
            // NOTE: This occurs if the data recovery sequence is run during a mount operation.
        }
        else if(result <= nn::fs::ResultMediaAccessError())
        {
            // This error is only returned when the cause is hardware related, such as a poor connection.
            // In such cases, recovery may be possible by re-inserting the SD Card, restarting the system, or some other action.
        }
        else
        {
            // The file or directory on the SD card may be read-only.
            // NOTE: This occurs if the data recovery sequence is run during a mount operation.
        }
    }
    else
    {
        // Unexpected error if other than the above. Failed to recognize this expanded save data or SD Card.
        // Do not call "NN_ERR_THROW_FATAL" macros.
    }

    // Troubleshooting after data has been created. 
    if(result.IsFailure())
    {
        if(result <= nn::fs::ResultNotEnoughSpace())
        {
            // The SD Card does not have the necessary free space.
        }
        else if(result <= nn::fs::ResultNotFormatted())
        {
            // An error has occurred, interrupting the process of data creation.
        }
        else if(result <= nn::fs::ResultOperationDenied())
        {
            if(result <= nn::fs::ResultWriteProtected())
            {
                // The SD Card is write-protected.
            }
            else if(result <= nn::fs::ResultMediaAccessError())
            {
                // This error is only returned when the cause is hardware related, such as a poor connection.
                //       In such cases, recovery may be possible by retrying, re-inserting the Game Card, restarting the system, or some other action.
            }
            else
            {
                // The directory on the SD Card may be read-only.
                // NOTE: This occurs if the data recovery sequence is run during a mount operation.
            }
        }
        else
        {
            // Failed to recognize this expanded save data or SD Card.
            // Handle corresponding errors here together. Do not jump to the fatal error screen.)
            // NOTE: When developing your application, confirm that valid values are passed to iconData and iconDataSize.
        }
    }
    else
    {
        // Remount
        result = nn::fs::MountExtSaveData();
        if(result.IsFailure())
        {
            // The same as when making the first call.
            // (Supplement) As long as the SD Card is not removed, mount operations carried out immediately after the data is created will never fail.
        }
    }
}

Write-only SDMC Archives

nn::Result result = nn::fs::MountSdmcWriteOnly();

if(result.IsFailure())
{
    if(result <= nn::fs::ResultMediaNotFound())
    {
        // An SD Card has not been inserted.
        // NOTE: This error is also returned if the SD Card is damaged or if some medium other than an SD Card is inserted.
        //        In such cases, an insertion event registered by RegisterSdmcInsertedEvent is signaled.
    }
    else if(result <= nn::fs::ResultBadFormat())
    {
        // You must format the SD Card.
    }
    else if(result <= nn::fs::ResultOperationDenied())
    {
        if(result <= nn::fs::ResultWriteProtected())
        {
            // This error will not be returned when mounted. Check separately by calling the nn::fs::IsSdmcWritable function.
        }
        else if(result <= nn::fs::ResultMediaAccessError())
        {
            // This error is only returned when the cause is hardware related, such as a poor connection.
            // In such cases, recovery may be possible by re-inserting the SD Card, restarting the system, or some other action.
        }
        else
        {
            // Failed to recognize this SD Card.
            // Handle corresponding errors here together. Do not jump to the fatal error screen.)
        }
    }
    else
    {
        // Failed to recognize this SD Card.
        // Handle corresponding errors here together. Do not jump to the fatal error screen.)
    }
}

Handling Errors During File and Directory Operations

The following simplified C++ code provides a guideline for handling errors during file and directory operations.


There are two types of functions used to perform file and directory operations: Try functions (which have the prefix Try added to the function name), and non-Try functions (which do not contain this prefix). For details, see Functions for File and Directory Operations.

ROM Archives

// Because errors are handled internally by non-Try functions, you do not need to receive Result values.
nn::fs::XXX();

Save Data Archives

// We need to use Try functions with save data archive.
result = nn::fs::TryXXX();

if(result.IsFailure())
{
    if(result <= nn::fs::ResultNotFound())
    {
        // The specified path does not exist.
        // Note: This error is returned when creating a file or directory and the archive name is wrong or a directory in the path does not exist.
    }
    else if(result <= nn::fs::ResultAlreadyExists())
    {
        // The specified path already exists.
        // NOTE: This error is not returned when files and directories are deleted.
    }
    else if(result <= nn::fs::ResultVerificationFailed())
    {
        // If there is automatic redundancy, you must reformat because otherwise the save data will not be completely consistent.
        // If there is no automatic redundancy, you must delete and recreate this file or directory.
        // CAUSE: The save data has been corrupted or tampered with.
        // NOTE: This state will never be caused by user operations (such as removing a card or turning off the system while data is being written) when there is automatic redundancy (unless intentionally tampered with).
        //       If there is no automatic redundancy, this error can occur even through normal user operations.
        //       If this is not resolved, you must format the save data.
        // NOTE: This error is returned when reading a region that has never been written to.
        // Be careful after executing the functions nn::fs::TryCreateFile and nn::fs::FileStream::TrySetSize.
    }
    else if(result <= nn::fs::ResultOperationDenied())
    {
        if(result <= nn::fs::ResultMediaAccessError())
        {
            // As of CTR-SDK 2.1, this error is handled by the system. Treat it as an unexpected error.
            NN_ERR_THROW_FATAL_ALL(result);
        }
        else
        {
            // Access was denied for some reason.
            // EXAMPLE: You attempted to delete a file that was open elsewhere.
            //           You attempted to move a file or directory so that it would span archives.
            //           You attempted to delete the root directory.
            // NOTE: You do not need handling for the above situations if, by design, they will not occur.
        }
    }
    else if(result <= nn::fs::ResultNotEnoughSpace())
    {
        // There is no available space in the archive or on the storage media.
        // NOTE: This error may occur when creating a file or directory, or changing the file size.
        //       If this error occurs when you create a file, delete the file because it might be corrupted.
        //       If this error occurs when you change the size of a file, the file may have grown to the maximum possible size.
    }
    else
    {
        // Unexpected error if other than the above.
        NN_ERR_THROW_FATAL_ALL(result);
    }
}

Expanded Save Data Archives

result = nn::fs::TryXXX();

if(result.IsFailure())
{
    if(result <= nn::fs::ResultNotFound())
    {
        if(result <= nn::fs::ResultMediaNotFound())
        {
            // An SD Card has not been inserted.
            // NOTE: This error is also returned if the SD Card is damaged or if some medium other than an SD Card is inserted.
            //        In such cases, an insertion event registered by RegisterSdmcInsertedEvent is signaled.
        }
        else
        {
            // The specified path does not exist.
            // NOTE: If this error is returned when opening the file, it may have been deleted from the SD Card using a PC or the like.
            // NOTE: Expanded save data can also be accessed from other applications,
            // so handling is not required for this error.
        }
    }
    else if(result <= nn::fs::ResultAlreadyExists())
    {
        // The specified path already exists.
        // NOTE: This error is not returned when directories are deleted.
        //       If this error is returned when creating a file, the file may have been deleted from the SD Card using a PC or the like.
        // NOTE: Expanded save data can also be accessed from other applications,
        // so handling is required for this error.
    }
    else if(result <= nn::fs::ResultVerificationFailed())
    {
        // You must delete and recreate this file or directory.
        // CAUSE: The expanded save data has been corrupted or tampered with.
        // NOTE: If this is not resolved, you need to recreate the expanded save data.
        // NOTE: This error is returned when reading a region that has never been written to.
        // Be careful after executing the functions nn::fs::TryCreateFile and nn::fs::FileStream::TrySetSize.
    }
    else if(result <= nn::fs::ResultArchiveInvalidated())
    {
        // You must remount the archive.
        // CAUSE: The SD Card was removed, making the archive invalid.
        // NOTE: Close all open files, call the nn::fs::Unmount function, and then remount the archive.
    }
    else if(result <= nn::fs::ResultOperationDenied())
    {
        if(result <= nn::fs::ResultWriteProtected())
        {
            // The SD Card is write-locked.
            // NOTE: This error occurs when you write to an SD Card. This does not occur when you simply open a file.
        }
        else if(result <= nn::fs::ResultMediaAccessError())
        {
            // This error is only returned when the cause is hardware related, such as a poor connection.
            // In such cases, recovery may be possible by re-inserting the SD Card, restarting the system, or some other action.
        }
        else
        {
            // Access was denied for some reason other than those above.
            // EXAMPLES: You attempted to write to a file that is read-only.
            //           You attempted to delete a file that was open elsewhere.
            //           You attempted to move a file or directory so that it would span archives.
            //           You attempted to delete the root directory.
            // (Note) Because the content of expanded save data can be modified even by other applications (depending on operations),
            // or a user may have spoofed data on the SD card using a PC, this error must always be handled
        }
    }
    else if(result <= nn::fs::ResultNotEnoughSpace())
    {
        // There is no available space in the archive or on the storage media.
        // NOTE: This error may occur when creating a file or directory, or changing the file size.
        //       If this error occurs when you create a file, delete the file because it might be corrupted.
        //       If this error occurs when you change the size of a file, the file may have grown to the maximum possible size.
    }
    else
    {
        // Failed to access this expanded save data or SD Card.
        // Handle corresponding errors here together. Do not jump to the fatal error screen.)
    }
}

Write-only SDMC Archives

result = nn::fs::TryXXX();

if(result.IsFailure())
{
    if(result <= nn::fs::ResultNotFound())
    {
        if(result <= nn::fs::ResultMediaNotFound())
        {
            // An SD Card has not been inserted.
            // NOTE: An SD Card may have been removed after the archive was mounted.
        }
        else
        {
            // The specified path does not exist.
            // NOTE: You must handle this error, because it is possible for users to manipulate data on SD Cards.
        }
    }
    else if(result <= nn::fs::ResultAlreadyExists())
    {
        // The specified path already exists.
        // NOTE: This error is not returned when files and directories are deleted.
        // NOTE: You must handle this error, because it is possible for users to manipulate data on SD Cards.
    }
    else if(result <= nn::fs::ResultArchiveInvalidated())
    {
        // You must remount the archive.
        // CAUSE: The SD Card was removed, making the archive invalid.
        // NOTE: Close all open files, call the nn::fs::Unmount function, and then remount the archive.
    }
    else if(result <= nn::fs::ResultOperationDenied())
    {
        if(result <= nn::fs::ResultWriteProtected())
        {
            // The SD Card is write-locked.
            // NOTE: This error occurs when you write to an SD Card. This does not occur when you simply open a file.
        }
        else if(result <= nn::fs::ResultMediaAccessError())
        {
            // This error is only returned when the cause is hardware related, such as a poor connection.
            // In such cases, recovery may be possible by re-inserting the SD Card, restarting the system, or some other action.
        }
        else
        {
            // Access was denied for some reason other than those above.
            // EXAMPLES: You attempted to write to a file that is read-only.
            //           You attempted to delete a file that was open elsewhere.
            //           You attempted to move a file or directory so that it would span archives.
            //           You attempted to delete the root directory.
            // NOTE: You must handle this error, because it is possible for users to manipulate data on SD Cards.
        }
    }
    else if(result <= nn::fs::ResultNotEnoughSpace())
    {
        // There is no available space in the archive or on the storage media.
        // NOTE: This error may occur when creating a file or directory, or changing the file size.
        //       If this error occurs when you create a file, delete the file because it might be corrupted.
        //       If this error occurs when you change the size of a file, the file may have grown to the maximum possible size.
    }
    else
    {
        // Failed to access this SD Card.
        // Handle corresponding errors here together. Do not jump to the fatal error screen.)
    }
}

Revision History

2012/04/26
Revised the method for handling operations on files/directories for save data archives.
2012/02/16
Added the section Save Data Archives (Other Programs).
2011/06/14
Added the fact that ResultVerificationFailed may occur when mounting duplicated save data.
2011/06/14
Added write-only SDMC archives.
Added note about handling fatal errors.
2011/03/14
Removed ResultMediaAccessError from the results when mounting save data and when operating on files and directories.
2011/03/07
Deleted ResultArchiveInvalidated from the errors that can occur in functions to create or delete expanded save data.
2011/02/28
Revised error handling for mounting ROM archives in accordance with changes to API.
2011/02/07
Changed how mounting expanded save data is handled from recreating the archive using ResultBadFormat to formatting the SD card.
Deleted ResultBadFormat from how manipulating expanded save data files and directories are handled.
Revised code so that unexpected errors now result in NN_ERR_THROW_FATAL_ALL.
2011/01/05
Deleted ResultArchiveInvalidated from the errors that can occur when mounting the expanded save data.
Changed the Result from ResultMediaAccessError to ResultMediaNotFound when a damaged SD Card is inserted.
2010/12/14
Added errors that must not be allowed to occur in retail products.
Added ResultNotFormatted and ResultArchiveInvalidated to error handling when expanded save data is created.
2010/12/13
Split up error handling for file and directory operations by archive type.
Changed how ResultOperationDenied is handled when expanded save data is mounted.
2010/12/09
Added Functions for File and Directory Operations.
2010/12/02
Removed ResultNotFound from save data error handling.
2010/11/31
Added ResultNotEnoughSpace to the errors occurring during file operations.
2010/11/25
Added ResultNotFormatted to error handling for expanded save data.
2010/11/13
Initial version.

CONFIDENTIAL