This is the 26th day of my participation in Gwen Challenge

Exception handling

  • Defined in the Java class libraryCheck in advanceRuntimeException should not be handled by catch:
    • NullPointerException
    • IndexOutofBoundsException
    • Exceptions that do not pass the pre-check are: When parsing string numbers, you have to do it by catching NumberFormatException
if(obj ! =null) {}
Copy the code
  • Exceptions should not be used for process control, condition control:
    • The original intention of exception design is to solve all kinds of unexpected situations in program operation, and the efficiency of exception processing is much lower than the condition judgment method
  • usecatchTo distinguish stable code from unstable code:
    • Stable code: Code that can’t go wrong no matter what
    • Unstable code: Catch of unstable code can distinguish the exception type as much as possible, and then do corresponding processing
    • A try-catch for a large chunk of code prevents the program from responding correctly to different exceptions and is not conducive to locating problems
      • In the user registration scenario, if the user enters illegal characters, or the user name already exists, or the user password is too simple, the program classifies and prompts the user
  • Catch exceptions for handling, don’t catch nothing. If no processing is required, the exception should be thrown to the caller
    • The outermost business consumer must handle the exception and turn it into something that the user can understand
  • If a try block is placed in the transaction code, it is important to roll back the transaction manually after a catch exception
  • finallyBlocks must be closed on resource objects, stream objects, and exceptionstry – catch
    • After JDK 7, you can use the try-with-resources approach
  • Don’t infinallyBlock the use ofreturn:
    • After a return ina finally block, the method completes execution. The return statement in the try block is not executed
  • The caught and thrown exceptions must match exactly, or be the parent of the thrown exception
  • The return value of a method can be null. It is not mandatory to return an empty collection or an empty object
    • Even if the calling method returns an empty collection or an empty object, it is important for the caller to consider null scenarios for remote call failures, serialization failures, runtime exceptions, and so on
  • To prevent NPE exceptions, pay attention to the following scenarios:
    • If the return type is basic data type, automatic unpacking may generate AN NPE
    • The database query result may be NULL
    • The element in the set, even if it’s isNotEmpty, can pull out data elements that are null
    • When a remote call returns an object, a null pointer must be checked to prevent AN NPE
    • You are advised to perform AN NPE check on the data obtained in the Session to avoid null Pointers
    • Cascade call obj.geta ().getb.getc (), a series of calls, easy to produce NPE
    • JDK 8 uses the Optional class to prevent NPE problems
  • Definition time distinctionuncheckedandcheckedException, avoid directly throwingnew RuntimeException(),Not allowed to throwExceptionorThrowable,Custom exceptions with business meaning should be used
    • Exceptions defined by the business world are recommended:
      • DAOException
      • ServiceException
  • For outside the companyHTTP or API open interfaceYou must use theError code; Application of internalrecommendedException throw;Across applicationsRPCCall takes precedence over useResultWay,Encapsulate isSuccess() method, error code, error brief message
    • The Result method is used for the following reasons:
      • With the throw exception return method, the caller will generate a runtime error if it is not caught
      • If you do not add stack information, just new custom exception, add their own understanding of the error message, for the caller to solve the problem will not be too much help. If stack information is added, performance loss in data serialization and transmission is also an issue in the case of frequent invocation errors
  • Avoid duplicate code, the DRY(Don’t Repeat Yourself) principle:
    • Duplicate code in the future modification, need to modify all copies, easy to miss
    • Extract common methods, or abstract common classes, or componentize
      • When there are multiple public methods in a class, all of which need to perform several lines of the same parameter verification, the extraction should be performed:
private boolean checkParam(DTO dto) {... }Copy the code

The log specification

  • In applications, the API of logging system (log4j, Logback) should not be directly used. Instead, the API of logging framework SLF4J should be used. The log framework in facade mode is conducive to unified maintenance and log processing of each class
  • Log files are kept for at least 15 days, as some exceptions occur in “weekly” intervals
  • Extension logs in applications (dosing, temporary monitoring, access logs, etc.)
    • appName_logType_logName.log
      • LogType: indicates the logType, such as stats,monitor, and access
      • LogName: log description
      • In this way, the file name can be used to know the application, type and purpose of the log file, and it can be easily classified and searched. Right
        • Run the following command to monitor the abnormal time zone conversion in the MPPServer application: mppServer_Monitor_timezoneconvert. log
      • You can classify logs, for example, storing error logs and service logs separately for developers to view and monitor the log system in a timely manner
  • righttrace,debug,infoLevel of log output, must use the conditional output format or use placeholder format
    logger.debug("Processing trade with id: " + id + " and symbol: " + symbol);
    Copy the code
    • If the log level is WARN: The above logs are not printed, but string concatenation operations are performed
    • If symbol were an object, the toString() method would be executed, wasting system resources by doing the above and not printing the log
    • Use conditional output form:
    if (logger.isDebugEnabled()) {
    	logger.debug("Processing trade with id: " + id + " and symbol: " + symbol);
    }
    Copy the code
    • Output using placeholders:
    logger.debug("Processing trade with id: {} and symbol: {}, id, symbol);
    Copy the code
  • To avoid repeating log printing and wasting disk space, you must set additivity=false in log4j.xml
<logger name="com.oxford.dubbo.config" additivity="false">
Copy the code
  • Exception information includes:
    • Crime scene information
    • Exception Stack information
    • If no, throw upwards using the exception keyword throws upward
Logger. error(various arguments or objects toString() +"_" + e.getMessage(), e);
Copy the code
  • Log carefully:
    • Debug logs cannot be generated in the production environment
    • Selectively output info logs
    • If you are usingwarnTo record the information about service behaviors when the server goes online, pay attention to the output of logs to avoid excessive server content, and delete these observation logs in time
      • A large number of invalid logs are generated, which is not conducive to system performance improvement or fault location
      • Consider the following when logging:
        • Do these logs really get read?
        • What can I do with this log?
        • Does it help troubleshoot the problem?
  • The WARN log level can be used to record user input parameter errors
  • Note the output level of the log:
    • The error level records only logical errors, exceptions, and major errors
  • Use full English to comment and describe log error messages