Last active
October 15, 2019 10:59
-
-
Save qlong8807/3b7ac1a3a7534aff15a0b99e0f2f512f to your computer and use it in GitHub Desktop.
SpringBoot2+ 统一异常处理
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.ytkj.abims.common.vo.Result; | |
import lombok.extern.slf4j.Slf4j; | |
import org.springframework.ui.Model; | |
import org.springframework.web.bind.WebDataBinder; | |
import org.springframework.web.bind.annotation.ExceptionHandler; | |
import org.springframework.web.bind.annotation.InitBinder; | |
import org.springframework.web.bind.annotation.ModelAttribute; | |
import org.springframework.web.bind.annotation.RestControllerAdvice; | |
/** | |
* 统一异常处理 | |
* 启动应用后,被 @ExceptionHandler、@InitBinder、@ModelAttribute 注解的方法,都会作用在 @RequestMapping 注解的方法上。 | |
*/ | |
@Slf4j | |
@RestControllerAdvice | |
public class UnionExceptionHandler { | |
/** | |
* 应用到所有@RequestMapping注解方法,在其执行之前初始化数据绑定器 | |
* | |
* @param binder | |
*/ | |
@InitBinder | |
public void initBinder(WebDataBinder binder) { | |
// log.info("binder.getFieldDefaultPrefix {}",binder.getFieldDefaultPrefix()); | |
// log.info("binder.getFieldMarkerPrefix {}",binder.getFieldMarkerPrefix()); | |
} | |
/** | |
* 把值绑定到Model中,使全局@RequestMapping可以获取到该值 | |
* ModelAttribute:在Model上设置的值,对于所有被 @RequestMapping 注解的方法中,都可以通过 ModelMap 获取 | |
* @param model | |
*/ | |
@ModelAttribute | |
public void addAttributes(Model model) { | |
model.addAttribute("author", "harry"); | |
} | |
/** | |
* Description : 全局异常捕捉处理 | |
*/ | |
@ExceptionHandler(Exception.class) | |
public Result apiExceptionHandler(Exception ex) { | |
log.error("ApiException 异常抛出", ex); | |
return Result.fail(ex.getMessage()); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment