@ControllerAdvice 全局异常处理

使用@ControllerAdvice 定义 全局异常处理

package com.app;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

/**
 * ContorllerAdvice 最常见的使用场景是全局异常处理
 * 一般搭配 @ExceptionHandler @ModelAttribute 以及 @InitBinder 使用
 * 如下是, 当单个文件超出最大size时 对应的自定义处理方法
 * 
 *  <p>By default the methods in an {@code @ControllerAdvice} apply globally to
 * all Controllers.
 * 
 * spring:
  servlet:
    multipart:
      max-file-size: 50KB  
 *
 */
@ControllerAdvice
public class CustomExceptionHandler {

    @ExceptionHandler(MaxUploadSizeExceededException.class)
    public void uploadException(MaxUploadSizeExceededException e, HttpServletResponse resp) throws IOException {
    resp.setContentType("text/html;charset=utf-8");
    PrintWriter out = resp.getWriter();
    out.write("文件大小超出限制!");
    out.flush();
    out.close();
    }
}

猜你喜欢

转载自www.cnblogs.com/luffystory/p/12010494.html