博客
关于我
SpringBoot全局统一异常处理(包含404错误处理)
阅读量:342 次
发布时间:2019-03-04

本文共 1768 字,大约阅读时间需要 5 分钟。

SpringBoot全局统一异常处理(包含404错误处理)

1.ControllerAdvice&&ExceptionHandler处理异常

package com.lius.controllers;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/exception")public class testExceptionColtroller {	@RequestMapping("/nullException")	public String nullException() {		//触发空指针异常		throw new NullPointerException("空指针异常!");	}}
package com.lius.handler;import java.util.HashMap;import java.util.Map;import org.springframework.web.bind.annotation.ExceptionHandler;import org.springframework.web.bind.annotation.ResponseBody;import org.springframework.web.bind.annotation.RestControllerAdvice;@RestControllerAdvice(basePackages = "com.lius.controllers")public class handlerException {	@ExceptionHandler(NullPointerException.class)	@ResponseBody	private Map
handlerNullPointException(){ Map
map = new HashMap<>(); map.put("code", 500); map.put("message", "代码错误,空指针异常!"); return map; }}

 

2.ErrorController拦截处理404异常

package com.lius.controllers;import java.util.HashMap;import java.util.Map;import org.springframework.boot.web.servlet.error.ErrorController;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;/** * 

处理404等error错误

* @author lius * */@Controllerpublic class errorController implements ErrorController { @Override public String getErrorPath() { // TODO Auto-generated method stub return "/error"; } @RequestMapping("/error") @ResponseBody public Map
handlerError(){ Map
errMap = new HashMap<>(); errMap.put("code", 404); errMap.put("message", "404页面未找到!"); return errMap; }}

 

转载地址:http://innq.baihongyu.com/

你可能感兴趣的文章
NFS
查看>>
nfs mount 故障 mount.nfs: access denied by server while mounting 10.0.100.208:/backup_usb
查看>>
NFS Server及Client配置与挂载详解
查看>>
NFS 服务配置篇
查看>>
NFS共享文件系统搭建
查看>>
nfs复习
查看>>
NFS安装配置
查看>>
NFS服务器配置-服务启动与停止
查看>>
NFS的安装以及windows/linux挂载linux网络文件系统NFS
查看>>
NFS的常用挂载参数
查看>>
NFS网络文件系统
查看>>
NFS远程目录挂载
查看>>
nft文件传输_利用remoting实现文件传输-.NET教程,远程及网络应用
查看>>
NFV商用可行新华三vBRAS方案实践验证
查看>>
ng build --aot --prod生成文件报错
查看>>
ng 指令的自定义、使用
查看>>
ng6.1 新特性:滚回到之前的位置
查看>>
nghttp3使用指南
查看>>
【Flink】Flink 2023 Flink 自动化运维的大规模落地实践
查看>>
Nginx
查看>>