Grails异常捕获

参考

捕获方式

  • 新建全局异常处理类
package com.jonny.common

import javassist.NotFoundException

import java.sql.BatchUpdateException
import java.sql.SQLException

/**
 * @Author Lee*
 * @Description 自定义异常处理类
 * @Date 2019年07月24日 20:22
 *
 */
trait GlobalExceptionHandler {

    def handleNotFoundExceptio(NotFoundException e) {
        response.status=404
        render ("error found")
    }

    def handleSQLException(SQLException e) {
        render 'A SQLException Was Handled'
    }

    def handleBatchUpdateException(BatchUpdateException e) {
        redirect controller: 'logging', action: 'batchProblem'
    }

    def handleNumberFormatException(NumberFormatException nfe) {
        [problemDescription: 'A Number Was Invalid']
    }

    def exceptionHandler(Exception e) {
        response.status = 500
        render e.getMessage()
    }
}
  • 实现异常类
package grails4.exception

import com.jonny.common.GlobalExceptionHandler
import javassist.NotFoundException

import java.sql.BatchUpdateException
import java.sql.SQLException

class TestController implements GlobalExceptionHandler {

    def index() {
        try {
            // do some work
            throw new NotFoundException("异常了")
        } catch (BatchUpdateException e) {
            return handleBatchUpdateException(e)
        } catch (SQLException e) {
            return handleSQLException(e)
        } catch (NumberFormatException e) {
            return handleNumberFormatException(e)
        } catch (NotFoundException e) {
            return handleNotFoundExceptio(e)
        }
    }

    def hello() {
        String abc = null
        abc.size()
    }
}

  • 日志
import grails.util.BuildSettings
import grails.util.Environment
import org.springframework.boot.logging.logback.ColorConverter
import org.springframework.boot.logging.logback.WhitespaceThrowableProxyConverter

import java.nio.charset.StandardCharsets

conversionRule 'clr', ColorConverter
conversionRule 'wex', WhitespaceThrowableProxyConverter

// 控制台日志
// See http://logback.qos.ch/manual/groovy.html for details on configuration
appender('STDOUT', ConsoleAppender) {
    encoder(PatternLayoutEncoder) {
        charset = StandardCharsets.UTF_8

        pattern =
                '%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} ' + // Date
                        '%clr(%5p) ' + // Log level
                        '%clr(---){faint} %clr([%15.15t]){faint} ' + // Thread
                        '%clr(%-40.40logger{39}){cyan} %clr(:){faint} ' + // Logger
                        '%m%n%wex' // Message
    }
}

// 输出日志
def targetDir = BuildSettings.TARGET_DIR
if (Environment.isDevelopmentMode() && targetDir != null) {
    appender("FULL_STACKTRACE", FileAppender) {
        file = "${targetDir}/stacktrace.log"
        append = true
        encoder(PatternLayoutEncoder) {
            charset = StandardCharsets.UTF_8
            pattern = "%level %logger - %msg%n"
        }
    }
    logger("StackTrace", ERROR, ['FULL_STACKTRACE'], false)

    // 日志位置
    logger("grails.app.controllers", DEBUG, ['FULL_STACKTRACE'],false)
}
root(ERROR, ['STDOUT','FULL_STACKTRACE'])